如何填充嵌套 json 对象 C#

How to populate Nested json object C#

嘿,我有一个class

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
  }
}

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

您在传入的 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);
        }
    }
}