Home > OS >  Deserialize json in C# for this array json format
Deserialize json in C# for this array json format

Time:09-28

How to deserialize this json format in C#?

How can we create a model for this type of json string and how to use that model to get the data?

[
     {
         "ID":"HR",
         "Province":"Haryana",
         "Capital":"Chandigarh"
     },
     {
         "ID":"BR",
         "Province":"Bihar",
         "Capital":"Patna"
     }
]

CodePudding user response:

try this

using Newtonsoft.Json;

var json=...your data

List<State> states = JsonConvert.DeserializeObject<List<State>>(json);

or using System.Text.Json

List<State> states = System.Text.Json.JsonSerializer.Deserialize<<List<State>>(json);

class

     public class State
    {
        public string ID { get; set; }
        public string Province { get; set; }
        public string Capital { get; set; }
    }

CodePudding user response:

Class:

 public class NameOfClass
{
    public string ID { get; set; }
    public string Province { get; set; }
    public string Capital { get; set; }
}

And then you can use this with yours jsonFile:

List<NameOfClass> nameOfVariable = JsonConvert.DeserializeObject<NameOfClass[]>(jsonFile).ToList();
  • Related