简体   繁体   English

如何将 Json 数组转换为 C# 中的对象列表

[英]How to convert Json array to list of objects in c#

I have Json string like below我有像下面这样的 Json 字符串

 {
"JsonValues":{

        "id": "MyID",

         "values": {
            "value1":{
                "id": "100",
                "diaplayName": "MyValue1"
            },
            "value2":{
                "id": "200",
                "diaplayName": "MyValue2"
            }
       }
}
}

I want to convert Json string to below classes我想将 Json 字符串转换为以下类

  class ValueSet
   {
    [JsonProperty("id")]
    public string id
    {
        get;
        set;
    }
    [JsonProperty("values")]
    public List<Value> values
    {
        get;
        set;
    }
  }

class Value
{
    public string id
    {
        get;
        set;
    }
    public string DiaplayName
    {
        get;
        set;
    }
}

My deserialization code is我的反序列化代码是

JavaScriptSerializer js = new JavaScriptSerializer();
        StreamReader sr = new StreamReader(@"ValueSetJsonString.txt");
        string jsonString = sr.ReadToEnd();
        var items = JsonConvert.DeserializeObject<ValueSet>(jsonString);

But I am getting null values after serialization, How i can solve this?但是序列化后我得到了空值,我该如何解决这个问题?

As others have already pointed out, the reason you are not getting the results you expect is because your JSON does not match the class structure that you are trying to deserialize into.正如其他人已经指出的那样,您没有获得预期结果的原因是您的 JSON 与您尝试反序列化的类结构不匹配。 You either need to change your JSON or change your classes.您需要更改 JSON 或更改您的类。 Since others have already shown how to change the JSON, I will take the opposite approach here.由于其他人已经展示了如何更改 JSON,因此我将在此处采用相反的方法。

To match the JSON you posted in your question, your classes should be defined like those below.为了匹配您在问题中发布的 JSON,您的类应该像下面那样定义。 Notice I've made the following changes:请注意,我进行了以下更改:

  1. I added a Wrapper class corresponding to the outer object in your JSON.我在你的 JSON 中添加了一个对应于外部对象的Wrapper类。
  2. I changed the Values property of the ValueSet class from a List<Value> to a Dictionary<string, Value> since the values property in your JSON contains an object, not an array.我将ValueSet类的Values属性从List<Value>更改为Dictionary<string, Value>因为 JSON 中的values属性包含一个对象,而不是数组。
  3. I added some additional [JsonProperty] attributes to match the property names in your JSON objects.我添加了一些额外的[JsonProperty]属性来匹配 JSON 对象中的属性名称。

Class definitions:类定义:

class Wrapper
{
    [JsonProperty("JsonValues")]
    public ValueSet ValueSet { get; set; }
}

class ValueSet
{
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("values")]
    public Dictionary<string, Value> Values { get; set; }
}

class Value
{
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("diaplayName")]
    public string DisplayName { get; set; }
}

You need to deserialize into the Wrapper class, not the ValueSet class.您需要反序列化为Wrapper类,而不是ValueSet类。 You can then get the ValueSet from the Wrapper .然后,您可以从Wrapper获取ValueSet

var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;

Here is a working program to demonstrate:这是一个工作程序来演示:

class Program
{
    static void Main(string[] args)
    {
        string jsonString = @"
        {
            ""JsonValues"": {
                ""id"": ""MyID"",
                ""values"": {
                    ""value1"": {
                        ""id"": ""100"",
                        ""diaplayName"": ""MyValue1""
                    },
                    ""value2"": {
                        ""id"": ""200"",
                        ""diaplayName"": ""MyValue2""
                    }
                }
            }
        }";

        var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;

        Console.WriteLine("id: " + valueSet.Id);
        foreach (KeyValuePair<string, Value> kvp in valueSet.Values)
        {
            Console.WriteLine(kvp.Key + " id: " + kvp.Value.Id);
            Console.WriteLine(kvp.Key + " name: " + kvp.Value.DisplayName);
        }
    }
}

And here is the output:这是输出:

id: MyID
value1 id: 100
value1 name: MyValue1
value2 id: 200
value2 name: MyValue2

http://json2csharp.com/ http://json2csharp.com/

I found the above link incredibly helpful as it corrected my C# classes by generating them from the JSON that was actually returned.我发现上面的链接非常有用,因为它通过从实际返回的 JSON 生成它们来纠正我的 C# 类。

Then I called :然后我打电话给:

JsonConvert.DeserializeObject<RootObject>(jsonString); 

and everything worked as expected.一切都按预期进行。

Did you check this line works perfectly & your string have value in it ?您是否检查过这条线是否完美运行并且您的字符串在其中有价值?

string jsonString = sr.ReadToEnd();

if yes, try this code for last line:如果是,请在最后一行尝试此代码:

ValueSet items = JsonConvert.DeserializeObject<ValueSet>(jsonString);

or if you have an array of json you can use list like this :或者如果你有一个 json 数组,你可以使用这样的列表:

List<ValueSet> items = JsonConvert.DeserializeObject<List<ValueSet>>(jsonString);

good luck祝你好运

Your data structure and your JSON do not match.您的数据结构和您的 JSON 不匹配。

Your JSON is this:你的 JSON 是这样的:

{
    "JsonValues":{
        "id": "MyID",
        ...
    }
}

But the data structure you try to serialize it to is this:但是您尝试将其序列化为的数据结构是这样的:

class ValueSet
{
    [JsonProperty("id")]
    public string id
    {
        get;
        set;
    }
    ...
}

You are skipping a step: Your JSON is a class that has one property named JsonValues , which has an object of your ValueSet data structure as value.您正在跳过一个步骤:您的 JSON 是一个具有名为JsonValues属性的类,该属性具有您的ValueSet数据结构的对象作为值。

Also inside your class your JSON is this:同样在你的课堂上,你的 JSON 是这样的:

"values": { ... }

Your data structure is this:你的数据结构是这样的:

[JsonProperty("values")]
public List<Value> values
{
    get;
    set;
}

Note that { .. } in JSON defines an object, where as [ .. ] defines an array.请注意,JSON 中的{ .. }定义了一个对象,而 as [ .. ]定义了一个数组。 So according to your JSON you don't have a bunch of values, but you have one values object with the properties value1 and value2 of type Value .因此,根据您的 JSON,您没有一堆值,但您有one values 对象,其属性value1value2的类型为Value

Since the deserializer expects an array but gets an object instead, it does the least non-destructive (Exception) thing it could do: skip the value.由于反序列化器需要一个数组,但获取的是一个对象,因此它会做它可以做的最少非破坏性(异常)的事情:跳过该值。 Your property values remains with it's default value: null .您的属性values保持其默认值: null

If you can: Adjust your JSON.如果可以:调整您的 JSON。 The following would match your data structure and is most likely what you actually want:以下将匹配您的数据结构,并且很可能是您真正想要的:

{
    "id": "MyID",

     "values": [
         {
            "id": "100",
            "diaplayName": "MyValue1"
         }, {
            "id": "200",
            "diaplayName": "MyValue2"
         }
     ]
}

Json Convert To C# Class = https://json2csharp.com/json-to-csharp Json 转换为 C# 类 = https://json2csharp.com/json-to-csharp

after the schema comes out模式出来后

        WebClient client = new WebClient();

        client.Encoding = Encoding.UTF8;

        string myJSON = client.DownloadString("http://xxx/xx/xx.json");

        var valueSet = JsonConvert.DeserializeObject<Root>(myJSON);

The biggest one of our mistakes is that we can't match the class structure with json.我们最大的错误之一是我们无法将类结构与 json 匹配。

This connection will do the process automatically.此连接将自动执行此过程。 You will code it later ;) = https://json2csharp.com/json-to-csharp您稍后将对其进行编码;) = https://json2csharp.com/json-to-csharp

that's it.就是这样。

you have an unmatched jSon string, if you want to convert into a list, try this你有一个不匹配的 json 字符串,如果你想转换成一个列表,试试这个

{
    "id": "MyID",

     "values": [
        {
            "id": "100",
            "diaplayName": "MyValue1",
        },
        {
            "id": "200",
            "diaplayName": "MyValue2",
        }
   ]    
}

This is possible too:这也是可能的:

using System.Web.Helpers;
var listOfObjectsResult = Json.Decode<List<DataType>>(JsonData);

This takes the JsonElement and deserializes it to List of objects.这需要 JsonElement 并将其反序列化为对象列表。

List<object> draftInvoices = JsonConvert.DeserializeObject<List<object>>(jsonDrafts.ToString());

Example:例子:

[HttpPost]
        [Route("CreateDraft")]
        public async Task<IActionResult> CreateDraft([FromBody] JsonElement jsonDrafts)
        {
            List<object> draftInvoices = JsonConvert.DeserializeObject<List<object>>(jsonDrafts.ToString());
             
          
                for (int i = 0; i < draftInvoices.Count; i++) 
                 {
                  ........
                 }  

You may use Json.Net framework to do this.您可以使用 Json.Net 框架来执行此操作。 Just like this :像这样 :

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

the home page : http://json.codeplex.com/主页: http : //json.codeplex.com/

the document about this : http://james.newtonking.com/json/help/index.html#关于这个的文件: http : //james.newtonking.com/json/help/index.html#

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

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