简体   繁体   English

如何将此json转换为C#对象

[英]How to convert this json into C# object

I am receiving this JSON from third party hence have no control over it, 我从第三方收到此JSON,因此无法对其进行控制,

{
    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, 现在,我试图将其转换为C#对象,

[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. 问题是,即使JSON本身有很多内容,我也得到的类别计数为零。

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. 还值得注意的是,如果没有用引号引起来的字符串,您的json实际上是无效的。 I also used JSON.Net, but that should be irrelevant. 我还使用了JSON.Net,但这应该无关紧要。

[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 . 使用Json.NET

Deserializing a Json to an object becomes as easy as: 将Json反序列化为对象变得很容易:

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. 只要您在代码中定义了Json,NET就会将任何Json转换为对象。 Account in this case can be anything, RootObject in your case. 在这种情况下, Account可以是任何东西,在您的情况下,可以是RootObject Also it will probably return some useful exceptions, if something with your Json doesn't fit the standard. 如果您的Json内容不符合标准,它也可能会返回一些有用的异常。

Invalid json , strings need to be enclosed in " . 无效的json ,字符串需要包含在"

You can test your json here: 您可以在此处测试json

https://jsonlint.com/ 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: 使用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. 在这里,您可以找到许多方法来完成您想要的事情,我个人很喜欢JavaScriptJsonSerializer。 enter link description here 在此处输入链接说明

Using JavaScriptJsonSerializer 使用JavaScriptJsonSerializer

JavaScriptSerializer is a class which helps to serialize and deserialize JSON. JavaScriptSerializer是一个类,可以帮助序列化和反序列化JSON。 It is present in namespace System.Web.Script.Serialization which is available in assembly System.Web.Extensions.dll. 它存在于名称空间System.Web.Script.Serialization中,该名称空间可在程序集System.Web.Extensions.dll中使用。 To serialize a .Net object to JSON string use Serialize method. 要将.Net对象序列化为JSON字符串,请使用Serialize方法。 It's possible to deserialize JSON string to .Net object using Deserialize or DeserializeObject methods. 可以使用Deserialize或DeserializeObject方法将JSON字符串反序列化为.Net对象。 Let's see how to implement serialization and deserialization using JavaScriptSerializer. 让我们看看如何使用JavaScriptSerializer实现序列化和反序列化。

Following code snippet is to declare custom class of BlogSites type. 以下代码段是声明BlogSites类型的自定义类。

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. 在序列化中,它将自定义.Net对象转换为JSON字符串。 In the following code, it creates an instance of BlogSiteclass and assigns some values to its properties. 在下面的代码中,它将创建BlogSiteclass的实例,并为其属性分配一些值。 Then we create an instance of JavaScriptSerializer and call Serialize() method by passing object(BlogSites). 然后,我们创建JavaScriptSerializer的实例,并通过传递object(BlogSites)来调用Serialize()方法。 It returns JSON data in string format. 它以字符串格式返回JSON数据。

// 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. 在反序列化中,它执行与序列化相反的操作,这意味着它将JSON字符串转换为自定义.Net对象。 In the following code, it creates JavaScriptSerializer instance and calls Deserialize() by passing JSON data. 在以下代码中,它将创建JavaScriptSerializer实例,并通过传递JSON数据来调用Deserialize()。 It returns custom object (BlogSites) from JSON data. 它从JSON数据返回自定义对象(BlogSites)。

// 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 使用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. 删除DataContract代码以创建简单的类结构。

Deserialize the object using JSON.Net 使用JSON.Net反序列化对象

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

RootObject being your top level object. RootObject是您的顶级对象。

You should then be able to access it like any normal object, ie 然后,您应该可以像访问任何普通对象一样访问它,即

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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