我想从使用API的页面中读取,该API以下面的嵌套JSON格式提供结果:
{
"rootEntity": "function",
"count": 92516,
"header": ["eventNumber", "startDate", "eventType"],
"results": [
["40262-1", "Tuesday, December 12, 2017", "Corporate"],
["14361-1", "Monday, October 23, 2017", "School"],
["5014-1", "Friday, October 13, 2017", "Birthday"]
]
}
下面是我用来反序列化JSON的代码。但这是一个错误。我做错了什么?
using (StreamReader reader = new StreamReader(responseStream))
{
JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(reader));
reader.Close();
JArray jarr = (JArray)o["results"];
jsonString = String.Join("\\", jarr);
}
jsonString = jsonString.Trim('"');
var resp = JsonConvert.DeserializeObject<WebResp>(jsonString);
jsonResponse = resp.results.ToArray();
答案 0 :(得分:1)
我会创建一个类似下面的辅助方法,将响应流中的结果转换为List<Dictionary<string, string>>
:
static List<Dictionary<string, string>> GetResultsFromResponseStream(Stream responseStream)
{
using (StreamReader streamReader = new StreamReader(responseStream))
using (JsonReader jsonReader = new JsonTextReader(streamReader))
{
JObject obj = JObject.Load(jsonReader);
JArray keys = (JArray)obj["header"];
List<Dictionary<string, string>> results = obj["results"]
.Children<JArray>()
.Select(a => keys.Zip(a, (k, v) => new { Key = (string)k, Value = (string)v })
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value))
.ToList();
return results;
}
}
然后您可以像这样使用它,例如:
var results = GetResultsFromResponseStream(responseStream);
foreach (var item in results)
{
foreach (var kvp in item)
{
Console.WriteLine(kvp.Key + ": " + kvp.Value);
}
Console.WriteLine();
}
输出:
eventNumber: 40262-1
startDate: Tuesday, December 12, 2017
eventType: Corporate
eventNumber: 14361-1
startDate: Monday, October 23, 2017
eventType: School
eventNumber: 5014-1
startDate: Friday, October 13, 2017
eventType: Birthday