c# - Now to serialise property of my custom class type as string? -


i tried implement getobjectdata iserializable, couldn't working - serialises cdata object.

classes:

public class cdata : ixmlserializable, iserializable {     private string m_value;      //...      public override string tostring()     {         return m_value;     }      public void getobjectdata(serializationinfo info, streamingcontext context)     {         info.addvalue("", m_value);     } }  public class myclass {     public cdata cdata { get; set; }  } 

code:

myclass myclass = new myclass { cdata = "asd"}; string o = jsonconvert.serializeobject(myclass); // returns {"cdata":{"":"asd"}}, want {"cdata":"asd"} 

update. looking solution can avoid changing myclass, because have hundreds of cdata usages , looks more hack rather proper solution.

custom converter looks way go, have remember use custom converter when dealing classes has cdata properties. hoping there should simpler , nicer way of doing (e.g. tried set empty string in info.addvalue("", m_value) or possible there interface)

you @ building custom converter type: http://www.newtonsoft.com/json/help/html/customjsonconverter.htm

edit: don't know of other interface, , doesn't it's possible iserializable. jsonconvert can made pretty flexible. example:

class conv : jsonconverter {     public override void writejson(jsonwriter writer, object value, jsonserializer serializer)     {         writer.writevalue(((cdata)value).etc);     }      public override object readjson(jsonreader reader, type objecttype, object existingvalue, jsonserializer serializer)     {         throw new exception(); // didn't bother     }      public override bool canconvert(type objecttype)     {         return objecttype == typeof(cdata);     } }  class wrap {     public cdata test { get; set; } }  class cdata  {     public string etc { get; set; } } 

and just

jsonconvert.serializeobject(t3, formatting.indented, new conv()); 

if have many types want handle same way, make logic in canconvert , writejson more complicated, maybe using reflection.


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -