Search code examples
c#arraysjsonjson-deserialization

Deserializing a Json message from an IoT Device in C#


I am new to C# and I am trying to deserialize a message coming from a Raspberry Pi running Azure IoT Edge (I'm using Visual Studio 2019 with Newtonsoft.Json and Newtonsoft.Json.Linq). However, I am unable to retrieve values from the message.

I have tried to convert it to an array and an object and then call the values.

The message is the following:

messageBody = "[{\"Tag\": \"Apple\", \"Probability\": 0.0012170099653303623}]"

And I used the following lines to deserialize it:

JArray jsonArray = JArray.Parse(messageBody);
var jsonObjects = jsonArray.OfType<JObject>().ToList();

And I would like to assign the attributes Tag and Probability to fruit and probability respectively.

string fruit = jsonObjects.Tag;
var probability = jsonObjects.Probability;

However, I get the error 'List does not contain a definition for Probabilty' and 'List does not contain a definition for Tag'


Solution

  • you can add new C# Class

    public class JsonModel{
    public string Tag {get;set;}
    public double Probability {get;set;}
    }
    
    var model = JsonConvert.DeserializeObject<List<JsonModel>>(message);