我有一个包含嵌套列表的对象和一个使用自定义转换器和.net的javascript序列化器从json反序列化它的方法。像这样:
public class MyObject{
int TheID { get; set; }
public List<MyNestedObject1> ListOfMyNestedObject1 { get; set; }
public List<MyNestedObject2> ListOfMyNestedObject2 { get; set; }
public MyObject ObjectFromJson(string TheObjectInJson) {
JavaScriptSerializer TheSerializer = new JavaScriptSerializer();
TheSerializer.RegisterConverters(new JavaScriptConverter[] {
new MyObjectConvert()
});
TheSerializer.RegisterConverters(new JavaScriptConverter[] {
new MyNestedObject1Convert()
});
TheSerializer.RegisterConverters(new JavaScriptConverter[] {
new MyNestedObject2Convert()
});
//if I comment out the registrations of the converters, it works
//but I need the converters of the nested objects to kick in
return TheSerializer.Deserialize<MyObject>(TheObjectInJson);
}
}
嵌套对象的json转换器如下所示:
public class MyNestedObject1Convert : JavaScriptConverter {
public override IEnumerable<Type> SupportedTypes {
get { return new Type[] { typeof(MyNestedObject1Convert) };
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{ //deserialization logic
return MyNestedObject1;}
}
MyObject的转换器如下所示:
public class MyObjectConvert : JavaScriptConverter {
public override IEnumerable<Type> SupportedTypes { get { return new Type[] { typeof(MyObjectConvert) }; }
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
int TheID;
MyObject TheObject = new MyObject();
int.TryParse(serializer.ConvertToType<string>(dictionary["TheID"]), out TheID))
TheObject.ID = TheID;
return TheObject;
}
}
现在,接收json字符串并看起来返回c#对象的调用函数如下所示:
MyObject AMyObject = new MyObject();
MyObject TheMyObject = new MyObject();
TheMyObject = AMyObject.ObjectFromJson(JsonString);
当我运行此代码时,返回的对象包含TheID,但嵌套对象为null。我在对象方法中注册转换器,但我猜这不是这样做的方法。如果我删除了转换器的注册,则对象包含嵌套对象,但转换器不会启动。
我需要改变什么?注意:我不打算使用其他库,只是为了使本机反序列化器工作。
感谢您的建议。
答案 0 :(得分:1)
好的,所以我让它上班了。如果您希望反序列化嵌套列表,可以按照以下方式进行操作。
首先,不要在MyObject ObjectFromJson方法中注册转换器。
其次,在MyObject的自定义转换器中,您可以对嵌套列表进行反序列化。像这样:
public class MyObjectConvert : JavaScriptConverter {
public override IEnumerable<Type> SupportedTypes { get { return new Type[] { typeof(MyObjectConvert) }; }
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
int TheID;
MyObject TheObject = new MyObject();
int.TryParse(serializer.ConvertToType<string>(dictionary["TheID"]), out TheID))
TheObject.ID = TheID;
if (dictionary.ContainsKey("ListOfMyNestedObject1"))
{
serializer.RegisterConverters(new JavaScriptConverter[] { new MyNestedObject1Convert() });
var TheList = serializer.ConvertToType<List<MyNestedObject1>>(dictionary["ListOfMyNestedObject1"]);
TheObject.ListOfMyNestedObject1 = TheList
}
return TheObject;
}
}
瞧:json使用.net的javascriptserializer使用自定义javascript转换器对嵌套列表进行反序列化。