Search code examples
c#asp.net-coredotnet-httpclient.net-6.0

Convert Json to List of Object


I am calling an API using:

HttpClient client = new HttpClient();

HttpResponseMessage response = await client.GetAsync(path);

String content = await response.Content.ReadAsStringAsync();

The returned content is the following Json:

{
  "sensors": [ 
   { "value": "1.2", "valid": "true" },
   { "value": "1.1", "valid": "false" },
   { "value": "1.7", "valid": "true" }
  ]
}

I need, for example, to sum the values of all sensors with valid equal to true.

Can I convert content to a list of objects and query it without defining a class for the type?


Solution

  • If you are looking for really dirty piece of code that "does that exactly" then here it is:

    // use package System.Text.Json
    var sum = JsonObject.Parse(json)["sensors"]
            .AsArray().OfType<JsonObject>()
            .Where(x => x["valid"].GetValue<string>() == "true")
            .Sum(x => double.Parse(x["value"].GetValue<string>()));
    

    But if you plan to work more on this code you are working on, please listen to other comments that suggest creating a C# class for Sensors and another for SensorValue and simply deserialize it.

    From the shape of JSON, it does not seems that there will be tons of data OR that performance is critical. Then deserializing JSON to some classes and processing those objects without craziness of plain JSON structures makes more sense.