使用JSON.Net从其包含的项中提取Array Name

时间:2015-10-19 21:02:29

标签: arrays json json.net

如果我从文件中读入了以下JSON对象,那么找到并返回" function"的数组名称的好方法是什么?如果我所知道的是元素: " functionId":null," name":" GameUpdate"和#34; GameEngine":"无"

{
  "data": [
    {
      "command": "Query",
      "Type": "Search",
      "id": null,
      "name": "Updates",
      "serviceType": "GameUpdates",
      "status": "Active",
      "isRunning": false,
      "server": "GameServer1",
      "function": [
        {
          "functionId": null,
          "name": "GameUpdate",
          "GameEngine": "None"
        }
      ],
      "system": "Game_System_007",
      "ProcessingTime": "2011-09-05T12:22:21.3809181-01:00",
      "Version": "v1.0"
    }
  ]
}

全部谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用Json.Net的LINQ-to-JSON API来查找它:

JObject obj = JObject.Parse(json);

string arrayName = obj["data"]
    .Children<JObject>()
    .SelectMany(jo => jo.Properties())
    .Where(jp => jp.Value.Type == JTokenType.Array && 
                 jp.Value.Children<JObject>()
                         .Any(jo => (string)jo["functionId"] == null && 
                                    (string)jo["name"] == "GameUpdate" && 
                                    (string)jo["GameEngine"] == "None"))
    .Select(jp => jp.Name)
    .FirstOrDefault();

Console.WriteLine(arrayName);

小提琴:https://dotnetfiddle.net/CffG0g