Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct format for empty GUIDs for JSON.NET to be deserialized?

Tags:

guid

json.net

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.

like image 292
Alexander Zeitler Avatar asked Apr 08 '12 13:04

Alexander Zeitler


People also ask

Is JSON serialized or Deserialized?

JSON is language independent and because of that, it is used for storing or transferring data in files. The conversion of data from JSON object string is known as Serialization and its opposite string JSON object is known as Deserialization.

How do I deserialize a JSON file?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is Jsonproperty annotation C#?

JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.

How does JSON serialization work?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.


1 Answers

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);
    }
}
like image 120
carlosfigueira Avatar answered Sep 21 '22 18:09

carlosfigueira