When I serialize a class object with the enum property for JSON, if the value is null, the resulting json borked

When I serialize a class object with the enum property for JSON, if the value is null, the resulting json string has a pair named name as follows:

"controlType":"-2147483648" 

This causes problems when I deserialize a string for a strongly typed object.

What is the best way to handle enumerations and zeros?

+6
json enums c #
source share
2 answers

the code below gives you json = ' {"Name": "Test", "Id": 1, "MyEnum": 3} ' if you have a non-zero 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 enumeration, when not set, is serialized to 0, while the enumeration itself starts at 1. So this is how the code can know that a NULL value was used for the enumeration.

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

+5
source share

Consider:

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

This gives:

 {"test":null} 

The best way to handle enumerations is with a key, an array of values, or stdClass. Just bind your names to a set of unique integers. Then you can link another direction:

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

This at least gives you bi-directionality.

0
source share

All Articles