如何反序列化此JSON?
{"totalResult":3,"categories":[{"1":{"categoryName":"plumbers","categoryIconUrl":"","headingName":"plumbers"}},{"2":{"categoryName":"plumbing parts and accessories","categoryIconUrl":"","headingName":"plumbing parts and accessories"}},{"3":{"categoryName":"plumbing services","categoryIconUrl":"","headingName":"plumbing services"}}]}
所以我已经尝试了几件事......目前我可以得到“totalResult”,但是我无法得到其他数据,这里是我用来获取我目前得到的信息的数据合同:
[DataContract]
public class categories_result
{
[DataMember(Name="totalResult")]
public int totalResult {get; set;}
[DataMember(Name="categories")]
public category[] results {get; set;}
}
[DataContract]
public class category
{
[DataMember(Name="categoryName")]
public string categoryName {get; set;}
[DataMember(Name="categoryIconUrl")]
public string categoryIconUrl {get; set;}
[DataMember(Name="headingName")]
public string headingName {get; set;}
}
当谈到类别类时,返回结果,我得到以下
- results {TrudonMobile.category[3]} TrudonMobile.category[]
- [0] {WP7proj.category} WP7proj.category
categoryIconUrl Could not evaluate expression string
categoryName Could not evaluate expression string
headingName Could not evaluate expression string
感觉我错过了一些东西,但我不确定。
增加:
我想我可能会在实际尝试反序列化的地方添加代码,因为这可能很有用:>
try
{
Stream responseStream = e.Result;
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(categories_result));
categories_result response = (categories_result)ser.ReadObject(responseStream);
}
catch (Exception x)
{
string bob = x.ToString();
return;
}
答案 0 :(得分:2)
使用Json.Net
string json =
@"
{
""totalResult"": 3,
""categories"": [
{
""1"": {
""categoryName"": ""plumbers"",
""categoryIconUrl"": """",
""headingName"": ""plumbers""
}
},
{
""2"": {
""categoryName"": ""plumbing parts and accessories"",
""categoryIconUrl"": """",
""headingName"": ""plumbing parts and accessories""
}
},
{
""3"": {
""categoryName"": ""plumbing services"",
""categoryIconUrl"": """",
""headingName"": ""plumbing services""
}
}
]
}
";
dynamic jObj = JsonConvert.DeserializeObject(json);
for (int i = 0; i < jObj.categories.Count; i++)
{
Console.WriteLine(jObj.categories[i][(i+1).ToString()].categoryName);
}
// OR
JObject jObj = (JObject)JsonConvert.DeserializeObject(json);
for (int i = 0; i < jObj["categories"].Count(); i++)
{
Console.WriteLine(jObj["categories"][i][(i+1).ToString()]["categoryName"]);
}
答案 1 :(得分:1)
尝试json.newtonsoft库
string data = "@:{"totalResult":3,"categories":[{"1":{"categoryName":"plumbers","categoryIconUrl":"","headingName":"plumbers"}},{"2":{"categoryName":"plumbing parts and accessories","categoryIconUrl":"","headingName":"plumbing parts and accessories"}},{"3":{"categoryName":"plumbing services","categoryIconUrl":"","headingName":"plumbing services"}}]} ";
JObject o = JObject.Parse(data);
JArray alldata = (JArray)(o["category"]);
访问类别类
中的成员 JObject first = (JObject)category[1];