12

使用 JSON.NET 将空 GUID 发送到服务器进行反序列化的正确格式是什么?

"{"id":"","name":"Test"}"结果是"Unrecognized Guid format."

"{"id":null,"name":"Test"}"结果是"Value cannot be null."

"{"id":"00000000-0000-0000-0000-000000000000","name":"Test"}"有效,但我不想强迫客户提供这个。

4

1 回答 1

20

您提到的格式确实是“正确”的格式。但是您也可以通过使用自定义来支持其他格式JsonConverter- 请参阅下面的代码以获取示例。

public class StackOverflow_10063118
{
    public class Foo
    {
        public Guid guid;
        public int i;

        public override string ToString()
        {
            return string.Format("Foo[i={0},guid={1}]", i, guid);
        }
    }
    class GuidConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(Guid) == objectType;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            switch (reader.TokenType)
            {
                case JsonToken.Null:
                    return Guid.Empty;
                case JsonToken.String:
                    string str = reader.Value as string;
                    if (string.IsNullOrEmpty(str))
                    {
                        return Guid.Empty;
                    }
                    else
                    {
                        return new Guid(str);
                    }
                default:
                    throw new ArgumentException("Invalid token type");
            }
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (Guid.Empty.Equals(value))
            {
                writer.WriteValue("");
            }
            else
            {
                writer.WriteValue((Guid)value);
            }
        }
    }
    public static void Test()
    {
        Foo foo = new Foo { guid = Guid.Empty, i = 123 };
        JsonSerializer js = new JsonSerializer();
        js.Converters.Add(new GuidConverter());
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        js.Serialize(sw, foo);
        Console.WriteLine(sb.ToString());
        StringReader sr = new StringReader(sb.ToString());
        Foo foo2 = js.Deserialize(sr, typeof(Foo)) as Foo;
        Console.WriteLine(foo2);
    }
}
于 2012-04-11T21:17:45.547 回答