【发布时间】:2020-05-11 08:13:01
【问题描述】:
我有以下 JSON,我试图在其中查询平均 confidence 值和 shape 对象的计数。我正在使用 Newtonsoft 创建 Json 对象并解析 Json 对象。我遇到错误“无法将 Newtonsoft.Json.Linq.JObject 转换为 Newtonsoft.Json.Linq.JToken”。我知道我将对象视为数组,因此会出现错误,但我不知道如何处理嵌套对象。请帮忙。
{
"channel":{
"description": "James Newton-King\"s blog.",
"region":[
{
"title": "Json.NET 1.3 + New license + Now on CodePlex",
"description": "Announcing the release of Json.NET 1.3",
"link": "http://james.newtonking.com/projects/json-net.aspx",
"shape":{
"square":{
"type":"number",
"text":"$81.22",
"confidence":0.983
},
"circle":{
"type":"string",
"valueString":"50741890",
"text":"50741890",
"confidence":1.0
},
"rectangle":{
"type":"date",
"text":"01/01/2020",
"confidence":1.0
}
}
}
],
"errors":[
]
}
}
//My code
public void qryNode()
{
string json = File.ReadAllText(@"C:\Extract.json");
JObject rss = JObject.Parse(json);
var categories =
from c in rss["channel"]["region"].SelectMany(i => i["shape"]).Values<string>()
group c by c
into g
orderby g.Count() descending
select new { Category = g.Key, Count = g.Count() };
foreach (var c in categories)
{
Console.WriteLine(c.Category + " - Count: " + c.Count);
}
}
【问题讨论】:
-
什么不适合你?
-
到目前为止您尝试了什么?你能改变这个json文件吗?我可以看到所有形状的共同属性,如果这是真的,那么
shapes将是 object 数组。这将使您的生活易于计算平均值 -
我们可以有“我正在使用 Newtonsoft [...] 解析 Json 对象。”部分吗?你有什么错误? minimal reproducible example