JSON.NET - asymmetric serialization


hi,

i'm having problems serializing , deserializing objects using json.net. need symmetric serialization, when deserialize object need exact copy of original object. not case.

the following code fails, because obj2.value of type long, should of type myenum:

public enum myenum  {      value1,      value2  }    public class myclass  {      public string name { get; set; }      [jsonproperty(typenamehandling= typenamehandling.objects)]      public object value { get; set; }  }    class program  {      static void main(string[] args)      {          var obj1 = new myclass { name = "name", value = myenum.value2 };          jsonserializersettings settings = new jsonserializersettings          {              typenamehandling = typenamehandling.all,              formatting = newtonsoft.json.formatting.indented          };          var json = jsonconvert.serializeobject(obj1, settings);          var obj2 = jsonconvert.deserializeobject<myclass>(json);          debug.assert(object.equals(obj1.value, obj2.value), "values don't match");      }  }

how can achieve symmetric serialization using json.net?

please help.

json.net stores type info sometimes, , not. simple types doesn't. root cause of issue. property value, not supposed of specific type, declared object, can of type, therefore type information needed deserialize it. if value of complex type such class several properties, there no problem, json.net includes type information automatically. if value of type enum or numeric, doesn't, deserializing in totally different type than the original one.

so, yes, seems need implement custom serialization. hoped easier.




Visual Studio Languages  ,  .NET Framework  >  Visual C#



Comments

Popular posts from this blog

Azure DocumentDB Owner resource does not exist

job syspolicy_purge_history job fail in sqlserver 2008

Trying to register with public marketplace error with 'Get-AzureStackStampInformation'