How can I deserialize using JSON.NET and save the parent

I have a JSON like:

{ "companyName": "Software Inc.", "employees": [ { "employeeName": "Sally" }, { "employeeName": "Jimmy" } ] } 

I want to deserialize it into:

 public class Company { public string companyName { get; set; } public IList<Employee> employees { get; set; } } public class Employee { public string employeeName { get; set; } public Company employer { get; set; } } 

How can I set the JSON.NET employer link? I tried using CustomCreationConverter , but the public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) does not contain any reference to the current parent object.

+4
source share
1 answer

This will only cause headaches if you try to do this as part of deserialization. It would be much easier to complete this task after deserialization. Do something like:

 var company = //deserialized value foreach (var employee in company.employees) { employee.employer = company; } 

Or single line if you prefer the syntax:

 company.employees.ForEach(e => e.employer = company); 
+1
source

Source: https://habr.com/ru/post/1479710/


All Articles