我正在处理来自Windows Phone 7客户端服务的JSON响应(如下所示)。我使用Json。NET将它们反序列化为一个对象,该对象包含产品列表。
但是在我反序列化之后,当我查看我的servicerresponse对象时,我可以看到一个包含2个产品的列表。但是当我展开产品对象时,product (Name, ExpiryDate…)下的字段等)都为空
我想我的问题是我定义servicerresponse类的方式。谁能帮我解决这个问题,得到正确的输出?
反序列化代码:
serviceresponse deserializedProduct = JsonConvert.DeserializeObject<serviceresponse>(json);
我的Json响应字符串:
{ "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;
}
从json中删除"product"
对象名称,因为这只是一个没有命名项的数组。
{ "serviceresponse" :
{ "company" : "ford", "success" : "Yes", "products" : [
{
"Name": "Product 1",
"ExpiryDate": "/Date(978048000000)/",
"Price": "99.95",
"Sizes": "1"
},
{
"Name": "Product 2",
"ExpiryDate": "/Date(1248998400000)/",
"Price": "12.50",
"Sizes": "1"
}
], "callbackformore" : "No", "message" : "1"
}
}
我最终这样做了。我发现了这个很棒的工具Jsonclassgenerator。它可以为输入Json字符串生成c#类。然后我打开生成的类,发现类是如何布局的。并相应地修改了我的Datacontract。
在我的例子中,我必须围绕对象列表创建另一个数据契约。所以应该是这样的
[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;
}