如何从JSON文件编写linq查询

wooyq4lh  于 2023-05-04  发布在  其他
关注(0)|答案(1)|浏览(141)

我有一个JSON文件。我想从验证中获取所有GUID列表。我试图得到验证的选项。然后使用id迭代此列表和所有Guid列表。items.FirstOrDefault(x =〉x.Key ==“validate”).Value.Options;如何编写LINQ查询。下面是JSON的示例。

{
"validation": {
          "options": [
            "Fail",
            "Success",
            "Resume"
          ],
          "extras": {
            "Fail" : {
            "id": "892DB3B6-BE0D-49F8-995A-50E921C2B778"
            },
             "Success" : {
            "id": "BC0EDB51-8317-4AFB-915F-B0579FADB500"
            },
             "Resume" : {
            "id": "59786216-FF4A-4E5C-ACB2-1BCE0A6E8D7d"
            }
          }
        }
        
        "vm": {
          "options": [
            "vm1",
            "vm2",
            "vm3"
          ],
          "extras": {
            "vm1" : {
            "id": "433DB3B6-BE0D-49F8-9D5A-50E921C2B999"
            },
             "Success" : {
            "id": "RT0EDB51-8317-4AFB-915F-B0579FADB888"
            },
             "Resume" : {
            "id": "44C86216-FF4A-4E5C-ACB2-1BCE0A6E9675"
            }
          }
        }
    }
6ojccjat

6ojccjat1#

首先,接收选项列表,然后接收基于该选项的id并使用“Newtonsoft.Json”

string RootName = "validation";
string extrasName = "extras";
string optionsName = "options";

JObject sample = (JObject)JsonConvert.DeserializeObject(jsonString);
IJEnumerable<JToken> items = sample[RootName][optionsName].Values();

List<Guid> result = new List<Guid>();

foreach (var content in items)
{
    var typeoptions = content.Value<string>();
    string valueitem = sample[RootName][extrasName][typeoptions]["id"].Value<string>();
        result.Add(Guid.Parse(valueitem));
}

相关问题