[SOLVED] C# : How to Deserialize json data

Issue

This Content is from Stack Overflow. Question asked by ian

How to deserialized this type of json file

[{"data":{"CRC":"a459","PC":"3000","TID":"e2806810200000040a0652c8","antenna":3,"channel":922.75,"eventNum":396,"format":"epc","idHex":"e28068100000003c0a0652c8","peakRssi":-36,"phase":0.0,"reads":36},"timestamp":"2022-09-19T09:03:26.445+0700","type":"SIMPLE"}]
;[{"data":{"CRC":"a459","PC":"3000","TID":"e2806810200000040a0652c8","antenna":3,"channel":922.75,"eventNum":397,"format":"epc","idHex":"e28068100000003c0a0652c8","peakRssi":-36,"phase":0.0,"reads":36},"timestamp":"2022-09-19T09:03:31.476+0700","type":"SIMPLE"}]

I want to get antenna, TID into variable

Thank you



Solution

This json is a collection so you’ll need to deserialise it to a collection:

// List<Hdr>, not Hdr
var listOfHrds = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Hdr>>(json);
public class Hdr{
  public TagRead data { get; set; }
}      

Test:

var json = File.ReadAllText("data.json");

var listOfHdrs = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Hdr>>(json);

Console.WriteLine(listOfHdrs[0].data.TID); // Output: e2806810200000040a0652c8

public class Hdr{
  public TagRead? data { get; set; }
} 

public class TagRead{
     public string? TID { get; set; }
}


This Question was asked in StackOverflow by ian and Answered by tymtam It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?