我有一个包含其他对象列表的对象,如下所示:
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);
}
现在我有另一个正在获取MyObject的json字符串的类,我需要对字符串进行反序列化并从字符串中创建一个MyObject。
我知道有JSON.net和其他库可用,但我想使用.net的JavascriptSerializer。
假设转换器我也处理了deserializtion。我只是做这样的事情:
1)将FromJson方法添加到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)并在调用类中写下:
MyObject TheObject = new MyObject();
TheObject = TheObject.MyObjectFromJson(TheIncomingString);
我不知道该怎么办。这种方法会起作用吗?
感谢。
答案 0 :(得分:0)
除非您的Object1和Object2列表非常复杂,否则您可能不需要转换器。
这是我根据您的代码汇总的快速示例。请注意,反序列化器是静态的,因为您希望它创建一个新对象,并且您不能设置this
,因为它是只读的。
public class MyObject
{
public int Prop1 { get; set; }
public List<Object1> TheListOfObject1 { get; set; }
public List<Object2> TheListOfObject2 { get; set; }
public MyObject()
{
TheListOfObject1 = new List<Object1>();
TheListOfObject2 = new List<Object2>();
}
public string ToJson()
{
JavaScriptSerializer TheSerializer = new JavaScriptSerializer();
return TheSerializer.Serialize(this);
}
public static MyObject FromJson(string sValue)
{
JavaScriptSerializer TheSerializer = new JavaScriptSerializer();
return TheSerializer.Deserialize<MyObject>(sValue);
}
}
然后由
调用 MyObject oObject = new MyObject();
oObject.TheListOfObject1.Add(new Object1(1));
oObject.TheListOfObject2.Add(new Object2(2));
oObject.Prop1 = 3;
string sJSON = oObject.ToJson();
System.Diagnostics.Debug.WriteLine(sJSON);
oObject = MyObject.FromJson(sJSON);
System.Diagnostics.Debug.WriteLine(oObject.Prop1);