Home > Enterprise >  How to deserialize json file?
How to deserialize json file?

Time:03-15

I have json file, how can I deserialize this? As I understood json file had array which has 3 elements, but I didn't understand what is inside elements Id, Name, Driver and data inside Driver what is this (Driver) object?

[
   {
      "Id":1,
      "Name":"Renault Magnum",
      "Driver":{
         "Name":"John",
         "Surname":"Dou",
         "Age":35,
         "Experience":10
      },
      "State":"base"
   },
   {
      "Id":2,
      "Name":"Volvo FH12",
      "Driver":{
         "Name":"Jack",
         "Surname":"Dou",
         "Age":55,
         "Experience":30
      },
      "State":"base"
   },
   {
      "Id":3,
      "Name":"DAF XF",
      "Driver":{
         "Name":"Jane",
         "Surname":"Dou",
         "Age":45,
         "Experience":15
      },
      "State":"base"
   }
]

CodePudding user response:

You can use the Paste Special-Feature of Visual Studio to generate classes from a json. By applying this technique to the json above, you get the following classes as a result:

public class Rootobject
{
    public Class1[] Property1 { get; set; }
}

public class Class1
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Driver Driver { get; set; }
    public string State { get; set; }
}

public class Driver
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }
    public int Experience { get; set; }
}

This indicates that the answer to your question what is inside elements Id, Name, Drivder and data inside Driver what is this (Driver) object? is: Yes, it is an object.

I would recommend naming the elements in a useful way though ;-)

CodePudding user response:

I think this question has been answered many times, here are some useful links you can go through to get hand to hand with this problem,

Deserialize Json with c# Serialization and Deserialization in Json Serialization and Deserialization with Json in c# Follow this documentation for complete guide on how to use NewtonJson for serialization and deserialization purposes and many more.

  • Related