Json.NET:使用对象列表进行反序列化 [英] Json.NET: Deserialization with list of objects
问题描述
我正在从Windows Phone 7客户端上的服务处理JSON响应(如下所示).我正在使用Json.NET将它们反序列化为一个对象,该对象包含产品列表.
I am processing JSON responses (displayed below) from a service on my Windows Phone 7 client. I am using Json.NET to deserialize them into an object, which contains List of products.
但是在反序列化之后,当我查看服务响应对象时,可以看到2种产品的列表.但是当我扩展产品对象时,产品下的字段(名称,ExpiryDate ...等)都为空.
But after I deserialize, when I looked into my serviceresponse object, I can see a list of 2 products. But when I expand the product object, the fields under product (Name, ExpiryDate... etc ) are all null.
我想我的问题在于定义服务响应类的方式.有人可以帮助我解决问题并获得正确的输出.
I guess my problem is with the way I have defined my serviceresponse class. Can someone help me to resolve the issue and get the correct output.
我的反序列化代码:
serviceresponse deserializedProduct = JsonConvert.DeserializeObject<serviceresponse>(json);
我的Json响应字符串:
My Json response String:
{ "serviceresponse" :
{ "company" : "ford", "success" : "Yes", "products" : [
{"product" :
{
"Name": "Product 1",
"ExpiryDate": "\/Date(978048000000)\/",
"Price": "99.95",
"Sizes": "1"
}
},
{"product" :
{
"Name": "Product 2",
"ExpiryDate": "\/Date(1248998400000)\/",
"Price": "12.50",
"Sizes": "1"
}
}
], "callbackformore" : "No", "message" : "1"
}
}
我的服务响应类:
[DataContract]
public class serviceresponse
{
[DataMember]
public String company;
[DataMember]
public String success;
[DataMember]
public List<product> products;
[DataMember]
public String callbackformore;
[DataMember]
public String message;
}
[DataContract]
public class product
{
[DataMember]
public String Name;
[DataMember]
public String ExpiryDate;
[DataMember]
public String Price;
[DataMember]
public String Sizes;
}
推荐答案
我最终这样做了.我发现了这个很棒的工具 Jsonclassgenerator .它可以为输入的Json字符串生成C#类.然后,我打开生成的类,并发现如何布置这些类.并相应地修改了我的Datacontract.
I ended up doing this. I found this awesome tool Jsonclassgenerator. It could generate C# classes for the input Json string. Then I opened the generated class and found how the classes are laid out. And modified my Datacontract accordingly.
就我而言,我必须围绕对象列表创建另一个数据协定.所以应该是这样.
In my case, I have to create another data contract surrounding the list of objects. So it should be like this.
[DataContract]
public class serviceresponse
{
[DataMember]
public String company;
[DataMember]
public String success;
[DataMember]
public List<product> products;
[DataMember]
public String callbackformore;
[DataMember]
public String message;
}
[DataContract]
public class product
{
[DataMember(Name = "product")]
public product2 _product;
}
[DataContract(Name = "product")]
public class product2
{
[DataMember]
public String Name;
[DataMember]
public String ExpiryDate;
[DataMember]
public String Price;
[DataMember]
public String Sizes;
}
这篇关于Json.NET:使用对象列表进行反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!