我需要一些解析JObject的帮助。以下json是c#中的这行代码的结果:
var o = JObject.Parse(data);
o {{
"firstdata": {
"count": 17,
"firstOccurrence": 1493663381786,
"lastOccurrence": 1493681141398
},
"views": {
"count": 17,
"firstOccurrence": 1493663381787,
"lastOccurrence": 1493681141398
},
"session": {
"count": 57,
"firstOccurrence": 1493663381787,
"lastOccurrence": 1493681159212
},
"test": {
"count": 17,
"firstOccurrence": 1493663381788,
"lastOccurrence": 1493681141399
},
"browser": {
"count": 17,
"firstOccurrence": 1493663381788,
"lastOccurrence": 1493681141399
},
"click": {
"count": 18,
"firstOccurrence": 1493663381805,
"lastOccurrence": 1493681141410
},
"click.Default": {
"count": 18,
"firstOccurrence": 1493663381805,
"lastOccurrence": 1493681141410
},
"click.6": {
"count": 18,
"firstOccurrence": 1493663381805,
"lastOccurrence": 1493681141410
},
"generic_Click.mail": {
"count": 4,
"firstOccurrence": 1493663488302,
"lastOccurrence": 1493675499011
},
"generic_Click.calander": {
"count": 3,
"firstOccurrence": 1493663649203,
"lastOccurrence": 1493675501110
},
"generic_Click.tweet": {
"count": 2,
"firstOccurrence": 1493663657444,
"lastOccurrence": 1493675577793
},
"generic_Click.facebook": {
"count": 3,
"firstOccurrence": 1493663840925,
"lastOccurrence": 1493677734366
}
}}
我需要的是查找以" generic_click"开头的这个json对象中的所有元素。并存储相应的"计数"值。我试图使用这行代码寻找其中一个,返回null。
var test = o.SelectToken("generic_Click.facebook");
我的猜测是" generic_Click.facebook"导致SelectToken将此视为路径,而不是要查找的名称。
有人可以帮帮我吗?我正试图找到一种方法来回归"计算"对于以" generic_Click。"
开头的这个json对象中的所有元素非常感谢
答案 0 :(得分:1)
要在键中选择带有句点的单个元素路径,只需从
切换选择过程 o.SelectToken("generic_Click.facebook")
到
o["generic_Click.facebook"]
选择包含关键字 generic_Click 的多个元素,您可以按如下方式使用linq
var o = JObject.Parse(data);
var genericClick = o.AsJEnumerable().Where(x=>x.Path.Contains("generic_Click"));
然后你可以循环遍历它们
foreach (var token in genericClick)
{
Console.Write(token.First()["count"]);
}
并获取计数元素。
我希望这会有所帮助。
答案 1 :(得分:1)
您可以使用LINQ查询将项目名称和计数收集到字典中:
Dictionary<string, int> dict = JObject.Parse(data).Properties()
.Where(p => p.Name.StartsWith("generic_Click"))
.ToDictionary(p => p.Name, p => (int)p.Value["count"]);
foreach (var kvp in dict)
{
Console.WriteLine(kvp.Key + ": " + kvp.Value);
}