使用Linq导航或转换JSON

yh2wf1be  于 2023-02-17  发布在  其他
关注(0)|答案(2)|浏览(108)

让我们考虑这个JSON

{
  "data": "014",
  "theme": "COLORADO CASUAL",
  "family": "2163",
  "category": "00",
  "compo_groups": [
    {
      "title": "HEAD024",
      "values": [
        {
          "perc": "100",
          "desc": "COMP036"
        }
      ]
    },
    {
      "title": "HEAD035",
      "values": [
        {
          "perc": "100",
          "desc": "COMP042"
        },
        {
          "perc": "50",
          "desc": "COMP043"
        }
      ]
    }
  ],
  "product_name": "D812",
  "supplier_code": "1011"
}

我需要检查我所有的组合都是100pc。在这个JSON中我有2组组合。第一组是正确的。我有一个元素是100pc。第二组是由2个元素组成的,总共是150pc。这是一个错误。
我需要用C#编写一个代码来检测错误。我可以写这个代码的大部分。我只是不知道如何转换这个JSON中的值列表,我可以用LinQ管理。

q3qa4bjr

q3qa4bjr1#

假设你使用的是最新版本的.NET(例如.NET6),那么你可以使用内置的System.Text.Json库来解析你的JSON输入。如果你需要使用JSON的其他部分,我建议你反序列化到具体的C#类中,这样你就可以得到正确的验证,智能感知和所有好东西。
但是,如果您只是想检查这些百分比,您可以直接使用STJ库,例如:

// Load JSON 
var json = "{...}";
var doc = JsonDocument.Parse(json);

// Manually walk the document to get the values you need and summarise
var result = doc.RootElement
    .GetProperty("compo_groups")
    .EnumerateArray()
    .Select(a => new 
    {
        Title = a.GetProperty("title").ToString(),
        Percentage = a.GetProperty("values")
            .EnumerateArray()
            .Select(v => double.Parse(v.GetProperty("perc").ToString()))
            .Sum()
    });

你可以像这样迭代这个结果:

foreach(var value in result)
{
    Console.WriteLine($"Title '{value.Title}' has a percentage of {value.Percentage}");
}

它将输出以下内容:

Title 'HEAD024' has a percentage of 100
Title 'HEAD035' has a percentage of 150
ct3nt3jp

ct3nt3jp2#

你不需要任何类来获取你想要的数据

using System.Text.Json;

List<string> titles = JsonNode.Parse(json)["compo_groups"].AsArray()
                         .Select(x => x["values"].AsArray())
                         .Where(v => v.Select(x => 
                          Convert.ToInt32(x["perc"].GetValue<string>())).Sum() > 100)
                         .Select(v => v.Parent["title"].GetValue<string>())
                         .ToList();  // result  ["HEAD035"]

using Newtonsoft.Json;

List<string> titles = JObject.Parse(json)["compo_groups"]
    .Select(x => x["values"])
    .Where(v => v.Select(x => (int)x["perc"]).Sum() > 100)
    .Select(v => v.Parent.Parent)
    .Select(p=> (string) p["title"]) // here you can select any data you need
    .ToList();  // result  ["HEAD035"]

相关问题