Thursday, March 31, 2011

Handling enums in JSON

When I serialize an object of a class with a enum property to JSON, if the value is null, the resulting json string has a name value pair like this:

"controlType":"-2147483648"

This causes issues when I deserialize the string to a strongly typed object.

What's the best way of handling enums and nulls?

From stackoverflow
  • Consider:

    echo json_encode(array("test"=>null));
    

    This produces:

    {"test":null}
    

    The best way to handle enums is with a key,value array or an stdClass. Just bind your names to a set of unique integers. You can then bind the other direction as well:

    {"A":1, "B":2, "C":3, 1:"A", 2:"B", 3:"C"}

    This at least gives you bi-directionality.

  • the below code gives you json = '{"Name":"Test","Id":1,"MyEnum":3}', when you have a non-null value.

         public enum SerializeObjTestClassEnum
     {
      one = 1, two, three, four
     }
    
     [Serializable]
     public class SerializeObjTestClass
     {
      public string Name { get; set; }
      public int Id { get; set; }
      public SerializeObjTestClassEnum MyEnum{ get; set; }
     }
    
     public void SerializeObject_Test_Basic_Object()
     {
      var obj = new SerializeObjTestClass { Id = 1, Name = "Test", MyEnum = SerializeObjTestClassEnum.three };
      var json = (new JavaScriptSerializer()).Serialize(obj);
     }
    


    this code gives you json = '{"Name":"Test","Id":1,"MyEnum":0}'

        var obj = new SerializeObjTestClass { Id = 1, Name = "Test" };
    

    Notice how the enum, when not set, is serialized to a 0, while the enum itself starts out at 1. So this is how you code can know a NULL value was used for the enum.

    if you want the json to look like '{"Name":"Test","Id":1,"MyEnum":null}', then you're going to need to fake it out by using a class wrapper around the Enum.

    dbkk : The wrapper `is Nullable`, replace `MyEnum` with `MyEnum?`.

0 comments:

Post a Comment