skip to Main Content

Let consider this 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"
}

I need to check that all my compositions are exactly 100pc. In this JSON I have 2 group of composition. The first one is correct. I have one element to 100pc. The second one is composed by 2 elements and total is 150pc. This is an error.

I need to write a code in C# that detect the error. I can write most part of this code. I just don’t know how to transform this JSON in list of values I can manage with LinQ.

2

Answers


  1. you don’t need any classes to get the data you want

    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"]
    

    or

    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"]
    
    Login or Signup to reply.
  2. Assuming you are using a recent version of .NET (e.g. .NET6) then you can use the built-in System.Text.Json libraries to parse your JSON input. If you need to use other parts of the JSON, I would recommend deserialising in to concrete C# classes so you get proper validation, IntelliSense and all that good stuff.

    However, if you simply want to check those percentages you can use the STJ library directly, something like this for example:

    // 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()
        });
    

    And you can iterate over that result like this:

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

    Which will output this:

    Title 'HEAD024' has a percentage of 100
    Title 'HEAD035' has a percentage of 150
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search