我有下面的JSON,用于查询平均置信度值和 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);
}
}
答案 0 :(得分:0)
一旦解析了JObject,就可以像这样获得请求的结果:
var jObject = JObject.Parse(json);
var shapes = jObject["channel"]["region"]
.SelectMany(j => j["shape"]);
var confidences = shapes
.SelectMany(s => s.Select(i => i["confidence"]
.Value<float>()))
.ToList();
var result = new
{
ShapesCount = confidences.Count,
AverageConfidence = confidences.Average()
};
答案 1 :(得分:0)
您可以使用这样的直接 LINQ 关键字轻松查询
考虑这个 JSON
{
"items": [
{
"id": "10",
"name": "one"
},
{
"id": "12",
"name": "two"
}
]
}
让我们像这样把它放在一个名为 json
的变量中,
JObject json = JObject.Parse("{'items':[{'id':'10','name':'one'},{'id':'12','name':'two'}]}");
您可以使用以下 LINQ 查询从名称为 "one"
的项目中选择所有 ID
var Ids =
from item in json["items"]
where (string)item["name"] == "one"
select item["id"];
然后,您将在 IEnumerable 列表中获得结果