简体   繁体   中英

How to convert this json into C# object

I am receiving this JSON from third party hence have no control over it,

{
    code: 200,
    message: success,
    data: {
        categories: {
            0: {
                prop1: 100,
                prop2: blah
            },
            1: {
                prop1: 100,
                prop2: blah
            }
                    // etc.. etc.. it may return around 100 or more categories or less
        }
    }
}

Now I am trying to convert it to C# object,

[DataContract]
public class Category
{
    [DataMember] public string prop1 { get; set; }
    [DataMember] public string prop2 { get; set; }
}

[DataContract]
public class Data
{
    [DataMember]
    public List<Category> categories { get; set; }
}

[DataContract]
public class RootObject
{
    [DataMember]
    public int code { get; set; }
    [DataMember]
    public string message { get; set; }
    [DataMember]
    public Data data { get; set; }
}

and code to convert it,

   var response = LoadPageAsync(url).Result;
   var serializer = new JavaScriptSerializer();
   var rootObject = serializer.Deserialize<RootObject>(response);

Problem is I am getting Categories count coming as zero even though there are many in JSON it self.

You need to change your list of categories to a dictionary. Tested the following code and I achieved deserialization as needed. It's also worth noting that your json is actually invalid without the quotes surrounding the strings. I also used JSON.Net, but that should be irrelevant.

[DataContract]
public class Category
{
    [DataMember] public string prop1 { get; set; }
    [DataMember] public string prop2 { get; set; }
}

[DataContract]
public class Data
{
    [DataMember]
    public Dictionary<int, Category> categories { get; set; }
}

[DataContract]
public class RootObject
{
    [DataMember]
    public int code { get; set; }
    [DataMember]
    public string message { get; set; }
    [DataMember]
    public Data data { get; set; }
}

static void Main(string[] args)
{
    var root = new RootObject()
    {
        code = 1,
        message = "test",
        data = new Data()
        {
            categories = new Dictionary<int, Category>()
            {
                { 0, new Category()
                    {
                        prop1 = "cat1prop1",
                        prop2 = "cat1prop2"
                    }
                },
                { 1,  new Category()
                    {
                        prop1 = "cat2prop1",
                        prop2 = "cat2prop2"
                    }
                }
            }
        }
    };
    var testJson = "{code: 200,message: \"success\",data: {categories: {0: {prop1: 100,prop2: \"blah\"},1: {prop1: 100,prop2: \"blah\"}}}}";
    var json = JsonConvert.SerializeObject(root);
    var testConvert = JsonConvert.DeserializeObject<RootObject>(testJson);
}

Use Json.NET .

Deserializing a Json to an object becomes as easy as:

string json = @"{
  'Email': 'james@example.com',
  'Active': true,
  'CreatedDate': '2013-01-20T00:00:00Z',
  'Roles': [
    'User',
    'Admin'
  ]
}";

Account account = JsonConvert.DeserializeObject<Account>(json);

Console.WriteLine(account.Email);
// james@example.com

As their own docs show.

Json.NET will convert any Json to an object, as long as you have it defined in your code. Account in this case can be anything, RootObject in your case. Also it will probably return some useful exceptions, if something with your Json doesn't fit the standard.

Invalid json , strings need to be enclosed in " .

You can test your json here:

https://jsonlint.com/

This is valid:

{
    "code": 200,
    "message": "success",
    "data": {
        "categories": {
            "0": {
                "prop1": 100,
                "prop2": "blah"
            },
            "1": {
                "prop1": 100,
                "prop2": "blah"
            }
        }
    }
}

Model:

public class Zero
    {

        [JsonProperty("prop1")]
        public int Prop1 { get; set; }

        [JsonProperty("prop2")]
        public string Prop2 { get; set; }
    }

    public class One
    {

        [JsonProperty("prop1")]
        public int Prop1 { get; set; }

        [JsonProperty("prop2")]
        public string Prop2 { get; set; }
    }

    public class Categories
    {

        [JsonProperty("0")]
        public Zero Zero { get; set; }

        [JsonProperty("1")]
        public One One { get; set; }
    }

    public class Data
    {

        [JsonProperty("categories")]
        public Categories Categories { get; set; }
    }

    public class Example
    {

        [JsonProperty("code")]
        public int Code { get; set; }

        [JsonProperty("message")]
        public string Message { get; set; }

        [JsonProperty("data")]
        public Data Data { get; set; }
    }

Using Newtonsoft Json:

var example = Newtonsoft.Json.JsonConvert.DeserializeObject<Example>(json);

here you can find many method to do what you want, i personally like JavaScriptJsonSerializer. enter link description here

Using JavaScriptJsonSerializer

JavaScriptSerializer is a class which helps to serialize and deserialize JSON. It is present in namespace System.Web.Script.Serialization which is available in assembly System.Web.Extensions.dll. To serialize a .Net object to JSON string use Serialize method. It's possible to deserialize JSON string to .Net object using Deserialize or DeserializeObject methods. Let's see how to implement serialization and deserialization using JavaScriptSerializer.

Following code snippet is to declare custom class of BlogSites type.

class BlogSites  
{  
    public string Name { get; set; }  
    public string Description { get; set; }  
}  

Serialization

In Serialization, it converts a custom .Net object to a JSON string. In the following code, it creates an instance of BlogSiteclass and assigns some values to its properties. Then we create an instance of JavaScriptSerializer and call Serialize() method by passing object(BlogSites). It returns JSON data in string format.

// Creating BlogSites object  
BlogSites bsObj = new BlogSites()  
{  
   Name = "C-sharpcorner",  
   Description = "Share Knowledge"  
};  



// Serializing object to json data  
JavaScriptSerializer js = new JavaScriptSerializer();  
string jsonData = js.Serialize(bsObj); // {"Name":"C-sharpcorner","Description":"Share Knowledge"} 

Deserialization

In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom .Net object. In the following code, it creates JavaScriptSerializer instance and calls Deserialize() by passing JSON data. It returns custom object (BlogSites) from JSON data.

// Deserializing json data to object  
JavaScriptSerializer js = new JavaScriptSerializer();  
BlogSites blogObject = js.Deserialize<BlogSites>(jsonData);  
string name = blogObject.Name;  
string description = blogObject.Description;




// Other way to whithout help of BlogSites class  
dynamic blogObject = js.Deserialize<dynamic>(jsonData);  
string name = blogObject["Name"];  
string description = blogObject["Description"];  

Using Json.NET

public class Category
{
    public string prop1;
    public string prop2;
}

public class Data
{
    public List<Category> categories;
}

public class RootObject
{
    public int code;
    public string message;
    public Data data;
}

Remove the DataContract code to make a simple class structure.

Deserialize the object using JSON.Net

RootObject data = JsonConvert.DeserializeObject<RootObject>(jsonString);

RootObject being your top level object.

You should then be able to access it like any normal object, ie

string firstProp1 = RootObject.data.categories[0].prop1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM