c# - JSON deserialise to an object with a private setter -


i'm having issue json , de-serialisation. i've got live production code uses message object pass information around 1 system another. id of message important used identify it. don't want setting id's , such made private setter.

my problem comes when trying deserialise json object , id not set. (obviously because it's private)

does 1 have suggestion best way proceed? i've tried using iserialisation , it's ignored. i've tried using datacontract fails because of external system getting data from.

my option on table @ moment make id , timecreated fields have public setters.

i have object such

message {   public message()   {     id = guid.newguid();     timecreated = datetime.now();   }    guid id { get; private set; }    datetime timecreated { get; private set; }    string content {get; set;}  }    

now i'm using following code:

        var message = new message() { content = "hi" };         javascriptserializer jss = new javascriptserializer();          var msg = jss.serialize(message);         var msg2 = jss.deserialize<message>(msg);          assert.isnotnull(msg2);         assert.areequal(message.id, msg2.id); 

the id , time created fields not match because private. i've tried internal , protected no joy here either.

the full object has constructor accepts id , date time set these when loading them out of db.

any appreciated.

thank you

you can use datacontractjsonserializer instead of javascriptserializer. need decorate class data contract attributes.

    [datacontractattribute()]     public class message     {           public message()           {             id = guid.newguid();             timecreated = datetime.now;         }          [datamemberattribute()]         guid id { get; private set; }          [datamemberattribute()]         datetime timecreated { get; private set; }          [datamemberattribute()]         string content {get; set;}     }  

generic serialization helper methods

public static string tojsonstring(object obj) {     datacontractjsonserializer serializer = new datacontractjsonserializer(obj.gettype());     using (memorystream ms = new memorystream())     {         serializer.writeobject(ms, obj);         stringbuilder sb = new stringbuilder();         sb.append(encoding.utf8.getstring(ms.toarray()));         return sb.tostring();     } }  public static t toobjectfromjson<t>(string json) {     datacontractjsonserializer serializer = new datacontractjsonserializer(typeof(t));      using (memorystream ms = new memorystream(encoding.utf8.getbytes(json)))     {         return (t) serializer.readobject(ms);     } } 

in case, can deserialize using:

message msg = toobjectfromjson<message>(jsonstring); 

Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -