Search code examples
jsonasp.net-mvcasp.net-web-apijson2csharp

How to create Models in ASP.Net for multi level Json format?


Problem Specification: Build a web api in asp.net to post multi level json formatted data.

Json Format:

{
  "InfoList:"[
    {
    "Name": " Sample String 1",
    "URL": " Sample String2",
    "Info":[
        {
            "ZIP": " Sample String3 "
            "status": "Sample String4"
        }
    ]
     }
   ]
}

I tried to solve this problem. My models are given bellow:

My Models:

public class Information : InfoList
    {
        public InfoList InfoList { get; set; }
    }

public class InfoList 
        {

            public string Name { get; set; }

            public string URL { get; set; }

            public Info info { get; set; }
        }

public class Info
    {
        public string ZIP{ get; set; }

        public string status { get; set; }

    }

Those models Generates this kind of Json Format:

{
  "InfoList": {
    "Name": "sample string 1",
    "URL": "sample string 2",
    "Info": {
      "ZIP": "sample string 1",
      "status": "sample string 2"
    }
  },
  "Name": "sample string 1",
  "URL": "sample string 2",
  "Info": {
    "ZIP": "sample string 1",
    "status": "sample string 2"
  }
}

I need those parentheses exactly like the problem specification.What to do? I am working with ASP.Net Web API controller.


Solution

  • You just copy your JSON then create C# Class file. Then click Edit -> Paste Special -> Paste JSON as Classes. Thats it...

    You need Visual Studio for this.

    For more information please see below link

    How to show the "paste Json class" in visual studio 2012 when clicking on Paste Special?

    Valid JSON

    {
        "InfoList":  {
            "Name": " Sample String 1",
            "URL": " Sample String2",
            "Info": [
                {
                    "ZIP": " Sample String3 ",
                    "status": "Sample String4"
                }
            ]
        }
    }
    

    So your class must be like this.

    public class Rootobject
    {
        public Infolist InfoList { get; set; }
    }
    
    public class Infolist
    {
        public string Name { get; set; }
        public string URL { get; set; }
        public Info[] Info { get; set; }
    }
    
    public class Info
    {
        public string ZIP { get; set; }
        public string status { get; set; }
    }