Home > Back-end >  how to deserialize this JSON using Newtonsoft.Json C#?
how to deserialize this JSON using Newtonsoft.Json C#?

Time:12-20

how to deserialize this JSON using Newtonsoft.Json C#?

{
  "catalog": {
    "book": [
      {
        "id": "1",
        "author": "Autho1",
        "title": "GDB",
        "genre": "Kl",
        "price": "15",
        "publish_date": "1999-09-02",
        "description": "desc about book"
      },
      {
        "id": "2",
        "author": "Lil",
        "title": "JS",
        "genre": "DS",
        "price": "3.6",
        "publish_date": "1999-09-02",
        "description": "desc 2."
      }    
    ]
  }
}

I need to deserialize JSON into a structure, but in the end I have book = nil

CodePudding user response:

Okay, as documented at official docs of Newtonsoft.Json first of all for good code maintenance we should create a models that will describes all (or only needed to Domain/Buisness logic) data in C# class. For your example this is Book class

[JsonProperty("book")]
    public class Book
    {
        [JsonProperty("id")]
        public uint ID {get; set;} //GUID is better but, check how it's will be parsed 
        [JsonProperty("author")]
        public string Author {get; set;} // string can be replaced by Author model
        [JsonProperty("title")]
        public string Title {get; set;}
        [JsonProperty("genre")]
        public string Genre {get; set;} // string can be replaced by Enum
        [JsonProperty("price")]
        public double Price {get; set;}
        [JsonProperty("publish_date")]
        public string PublishDate {get; set;} // string can be replaced DateTime
        [JsonProperty("description")]
        public string Description {get; set;}
    }

And the catalog model

    public class Catalog
    {
        [JsonProperty("book")]
       public List<Book> Book {get; set;} = new List<Book>();
    }

After it you can do something kinda

string json = @"
{
  "catalog": {
    "book": [
      {
        "id": "1",
        "author": "Autho1",
        "title": "GDB",
        "genre": "Kl",
        "price": "15",
        "publish_date": "1999-09-02",
        "description": "desc about book"
      },
      {
        "id": "2",
        "author": "Lil",
        "title": "JS",
        "genre": "DS",
        "price": "3.6",
        "publish_date": "1999-09-02",
        "description": "desc 2."
      }    
    ]
  }
}";

Catalog catalog = JsonConvert.DeserializeObject<Catalog>(json);

There JsonProperty attribute (somewhere not required) is used for saying default parser to name of field in json, if object is reqired and order (as I can remember that's all.

I hope that your trouble is solved, pls read doc in next time and be more patient in your researches.

  • Related