Home > Software engineering >  Convert Json to List of Object
Convert Json to List of Object

Time:04-20

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?

CodePudding user response:

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().Where(x => x["valid"].GetValue() == "true").Sum(x => double.Parse(x["value"].GetValue()));

But if you plan to work more on this code you are working on, please listen to other comments that suggest to create 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 performance is critical. Then deserializing JSON to some classes and processing those objects without craziness of plain JSON structures makes more sense.

  • Related