我可能很傻,但我被困在这个上面。
我正在用 c# 编码并尝试将 JSON 字符串解析为对象。问题是字符串包含一个数据字段,我称之为伪数组。它不是一个真正的数组,因为它缺少 []。
我真的不想创建一个具有 500 个属性的对象,只是为了迎合我认为是 API JSON 响应中的错误 - 但是我到底如何将其反序列化为 c# 对象?
下面是 API 文档页面中的示例 JSON。(我不拥有 API - 所以我无法更改 JSON(
任何建议将不胜感激。谢谢K
'
{
"data": {
"71489": { <---- This is supposed to be an item in an array - but it isn't
"air_by_date": 0,
"cache": {
"banner": 1,
"poster": 1
},
"language": "en",
"network": "USA Network",
"next_ep_airdate": "",
"paused": 0,
"quality": "HD720p",
"show_name": "Law & Order: Criminal Intent",
"status": "Ended",
"tvdbid": 71489,
"tvrage_id": 4203,
"tvrage_name": "Law & Order: Criminal Intent"
},
"140141": {
"air_by_date": 0,
"cache": {
"banner": 0,
"poster": 0
},
"language": "fr",
"network": "CBS",
"next_ep_airdate": "2012-01-15",
"paused": 0,
"quality": "Any",
"show_name": "Undercover Boss (US)",
"status": "Continuing",
"tvdbid": 140141,
"tvrage_id": 22657,
"tvrage_name": "Undercover Boss"
},
...
"194751": {
"air_by_date": 1,
"cache": {
"banner": 1,
"poster": 1
},
"language": "en",
"network": "TBS Superstation",
"next_ep_airdate": 2011-11-28",
"paused": 0,
"quality": "Custom",
"show_name": "Conan (2010)",
"status": "Continuing",
"tvdbid": 194751,
"tvrage_id": 0,
"tvrage_name": ""
},
"248261": {
"air_by_date": 0,
"cache": {
"banner": 1,
"poster": 1
},
"language": "en",
"network": "Cartoon Network",
"next_ep_airdate": "",
"paused": 1,
"quality": "HD",
"show_name": "NTSF:SD:SUV::",
"status": "Continuing",
"tvdbid": 248261,
"tvrage_id": 28439,
"tvrage_name": "NTSF:SD:SUV"
}
},
"message": "",
"result": "success"
}
`
JSON 对象的 data
属性是一个关联数组。 您需要通过适当的键(在本例中为数字字符串(访问每个元素
// convert from a String into a JObject
var data = JObject.Parse(json);
// access single property
Response.Write(data["data"]["71489"]);
Response.Write(data["data"]["140141"]);
// iterate all properties
foreach (JProperty prop in data["data"])
{
Response.Write(prop.Name + ": " + prop.Value);
// Also possible to access things like:
// - prop.Value["air_by_date"]
// - prop.Value["cache"]["banner"]
// - prop.Value["cache"]["poster"]
// - prop.Value["language"]
}