c# - Proper Json.net System.Object Round-trip? -


using newtonsoft.json library, imagine have got

public class test {    public object obj { get; set; } } 

now, attempting serialize so

var json = jsonconvert.serializeobject(new test(){ obj = new uri(@"http://www.google.com") }); 

...will give me following json

{     "obj": "http://www.google.com" } 

which not enough information deserialize uri object, , in fact, attempting deserialize give me string object instead.

is there existing way correctly serialize , deserialize type information here object read in uri instead of string? in particular case, attempting interop .net application , extremely important exact types deserialized.

thanks in advance.

if want convert string uri, can use custom converter attribute

the converter

public class uriconverter : jsonconverter {     public override bool canconvert(type objecttype)     {         return true;     }      public override object readjson(jsonreader reader, type objecttype, object existingvalue, jsonserializer serializer)     {         if (reader.tokentype == jsontoken.string)         {             //try create uri out of string             uri uri;             if(uri.trycreate(reader.value.tostring(), urikind.absolute, out uri))             {                 return uri;             }             //just string -> return string value             return reader.value;         }          if (reader.tokentype == jsontoken.null)         {             return null;         }          throw new invalidoperationexception("unable process json");     }      public override void writejson(jsonwriter writer, object value, jsonserializer serializer)     {         if (null == value)         {             writer.writenull();             return;         }          if (value uri)         {             writer.writevalue(((uri)value).originalstring);             return;         }          throw new invalidoperationexception("unable process json");     } } 

and use attribute

 [jsonconverter(typeof(uriconverter))]  public object obj {get;set;} 

you should able determine whether underlying object uri like

  var data = jsonconvert.deserializeobject<yourobject>(yourjsonstring);   if (data.obj uri)   {        ... add logic here   }   else   {        ... not uri different logic   } 

you can check out article more information json.net uri (de)serialization errors


Comments