12

What's the correct format for empty GUIDs to be sent to the server using JSON.NET for deserialization?

"{"id":"","name":"Test"}" results in "Unrecognized Guid format."

"{"id":null,"name":"Test"}" results in "Value cannot be null."

"{"id":"00000000-0000-0000-0000-000000000000","name":"Test"}" works, but I don't want to force clients to provide this.

Alexander Zeitler
  • 11,919
  • 11
  • 81
  • 124

1 Answers1

20

The format you mentioned is indeed the "correct" one. But you can also support other formats by using a custom JsonConverter - see the code below for an example.

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);
    }
}
drzaus
  • 24,171
  • 16
  • 142
  • 201
carlosfigueira
  • 85,035
  • 14
  • 131
  • 171
  • fyi Resharper gives an ["impure method..." warning](http://stackoverflow.com/questions/9927434/impure-method-is-called-for-readonly-field) on `Guid.Empty.Equals(value)` – drzaus Feb 26 '15 at 22:25