I have an object that contains lists of other objects and that looks like this:
public class MyObject {
public int Prop1 { get; set; }
public List<Object1> TheListOfObject1 { get; set; }
public List<Object2> TheListOfObject2 { get; set; }
public string MyObjectInJson { get; set;}
public void MyObjectToJson()
{
JavascriptSerializer TheSerializer = new JavascriptSerializer();
TheSerializer.RegisterConverters(new JavaScriptConverter[] { new Object1ToJson() });
TheSerializer.RegisterConverters(new JavaScriptConverter[] { new Object2ToJson() });
MyObjectInJson = TheSerializer.Serialize(this);
}
Now I have another class that's getting a json string of MyObject and I need to deserializse the string and create a MyObject from the string.
I know there's JSON.net and other library available but I want to use .net's JavascriptSerializer.
Suppose that the converters I have also handle the deserializtion. Do I simply do something like this:
1) add FromJson method to MyObject
public this MyObjectFromJson (string MyObjectInJson)
{
JavascriptSerializer TheSerializer = new JavascriptSerializer();
TheSerializer.RegisterConverters(new JavaScriptConverter[] { new Object1ToJson() });
TheSerializer.RegisterConverters(new JavaScriptConverter[] { new Object2ToJson() });
this = TheSerializer.DeSerialize(MyObjectInJson);
}
2) and in the calling class write this:
MyObject TheObject = new MyObject();
TheObject = TheObject.MyObjectFromJson(TheIncomingString);
I'm not sure how to proceed. Will this kind of approach work?
Thanks.
JavascriptSerializer, but I have usedDataContractJsonSerializersuccessfully in a couple of projects, and it seems to be easier to use.