我正在从Windows Phone 7客户端上的服务处理JSON响应(如下所示)。我正在使用Json.NET将它们反序列化为一个对象,其中包含产品列表。
但是在反序列化之后,当我查看我的serviceresponse对象时,我可以看到2个产品的列表。但是当我展开产品对象时,product(Name,ExpiryDate ...等)下的字段都是null。
我想我的问题在于我定义了serviceresponse类的方式。有人可以帮我解决问题并获得正确的输出。
我的反序列化代码:
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;
}
答案 0 :(得分:3)
从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"
}
}
答案 1 :(得分:2)
我最终这样做了。我找到了这个很棒的工具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;
}