在 C# 中使用 SelectTokens 查询 JSON

Querying JSON with SelectTokens in c#

我需要一些关于解析 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
  }
}}

我需要的是在这个 json 对象中查找所有以 "generic_click" 开头的元素并存储它们对应的 "count" 值。我试图使用这行代码寻找其中之一,returns null.

var test = o.SelectToken("generic_Click.facebook");

我的猜测是 "generic_Click.facebook" 中的点导致 SelectToken 将其视为路径,而不是要查找的名称。

有人可以帮我解决这个问题吗?我正在尝试为这个 json 对象中以 "generic_Click."

开头的所有元素找到 return "count" 的方法

非常感谢

到 select 键中带有句点的单个元素路径只需将 selection 进程从

切换
 o.SelectToken("generic_Click.facebook")

 o["generic_Click.facebook"]

到select很多包含你关键字的元素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"]);
}

并获取您的 count 个元素。

希望对您有所帮助。

您可以使用 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);
}

Fiddle: https://dotnetfiddle.net/9Oq4J4