【问题标题】:How to populate Nested json object C#如何填充嵌套的 json 对象 C#
【发布时间】:2021-05-06 16:36:50
【问题描述】:

大家好,我有课

public class Data {

   string key {get; set;}
   string value {get; set;}
}
public class Employee { 

   string x {get; set;}
   string y {get; set;}
   Data Data {get; set;}
}

在 Json 响应中,我在字符串中得到以下值

{
  "Employee":{
  "x": null,
  "y": null,
  "Data" : {
    "key": 1,
    "Value": "hello"
    }
  }
}

我想将这个 Json 字符串反序列化为我使用的 Employee 类型

JsonConvert.DeserializeObject<Employee>(jsonString);

但它只填充父对象,嵌套对象数据为空,这里是结果

{
  "Employee":{
  "x": null,
  "y": null,
  "Data" :null
  }
}

有没有人有一些好的解决方案可以有效地获取嵌套对象的值。

【问题讨论】:

  • 数据在您的数据中大写,但在您的模型中小写。价值相同

标签: c# asp.net json.net


【解决方案1】:

传入的 Json 包中有错误。应该是这样的。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Newtonsoft.Json;

namespace Rextester
{
    public class Data {
       public string key {get; set;}
       public string value {get; set;}
    }
    public class Employee { 

       public string x {get; set;}
       public string y {get; set;}
       public Data Data {get; set;}
    }
    
    public class Program
    {
        public static void Main(string[] args)
        {
            string jsonString = @"{
              ""x"": null,
              ""y"": null,
              ""Data"" : {
                ""key"": 1,
                ""value"": ""hello""
                }
            }";
            
            var obj = JsonConvert.DeserializeObject<Employee>(jsonString);
    
            Console.WriteLine(obj.x);
            Console.WriteLine(obj.y);
            Console.WriteLine(obj.Data.key);
            Console.WriteLine(obj.Data.value);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2018-11-12
    • 2019-05-25
    • 2017-10-03
    • 1970-01-01
    • 2015-09-16
    • 2016-06-07
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    相关资源
    最近更新 更多