Home » c# » c# – How to assign class level property value to nested object properly through in deserialization

c# – How to assign class level property value to nested object properly through in deserialization

Posted by: admin February 21, 2020 Leave a comment

Questions:

Question: I wanted to assign the value of the employee.name to address.name through deserialization.

Inputs:

  var json = "{\"id\":1,\"name\":\"foo\",\"address\":{\"name\":\"\"}}";

Code:

  public class Employee  
   {  
     public int Id { get; set; }          
     public string Name { get; set; }  
     public Address Address { get; set; }  
   }  
public class Address  
{  
    public string Name { get; set; }  
}

var employeeObject = JsonConvert.DeserializeObject<Employee>(JsonConvert.SerializeObject(JObject.Parse(json)));

I want output would be like that

Employee = {
Id = 1,
Name ="foo",
Address = {Name = "foo"}
}
How to&Answers:

Try this:

var json = "{\"id\":1,\"name\":\"foo\",\"address\":{\"name\":\"\"}}";
var employeeObject = JsonConvert.DeserializeObject<Employee>(json);
employeeObject.Address.Name = employeeObject.Name;

Once you deserialize the object, you can assign employeeObject.Address.Name to employeeObject.Name.

###

Yout don’t require JsonConvert.SerializeObject(JObject.Parse. It should be –

var employeeObject = JsonConvert.DeserializeObject<Employee>(json);