简体   繁体   中英

How to populate Nested json object C#

Hey all I have a 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;}
}

In Json response I get the below value in string

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

I want to deserialize this Json string into type Employee I used

JsonConvert.DeserializeObject<Employee>(jsonString);

but It only populate the parent object and nested object data is null, here are results

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

Does anyone have some good solution to get the nested object value in an efficient way.

You have errors in the incoming Json package. It should be like this.

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

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