0

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.

1
  • 1
    Data is capitalized in your data, but lower case in your model. Same for value Commented May 6, 2021 at 16:42

1 Answer 1

0

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.