Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I deserialize using JSON.NET and preserve the parent object

Tags:

c#

json.net

I have some 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 have JSON.NET set the "employer" reference? I tried using a CustomCreationConverter, but the public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) method doesn't contain a any reference to the current parent object.

like image 434
marcprux Avatar asked May 08 '13 10:05

marcprux


People also ask

How do I deserialize JSON to an object?

NET objects (deserialize) A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is the difference between serialize and deserialize JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.

What is deserialization JSON?

The process whereby a lower-level format (e.g. that has been transferred over a network, or stored in a data store) is translated into a readable object or other data structure. In JavaScript, for example, you can deserialize a JSON string to an object by calling the function JSON.

Is polymorphic deserialization possible in system text JSON?

Text. Json doesn't support the serialization of polymorphic type hierarchies. For example, if a property's type is an interface or an abstract class, only the properties defined on the interface or abstract class are serialized, even if the runtime type has additional properties.


1 Answers

That's only going to cause you headaches if you're trying to do that as part of the deserialization. It'd be much easier to perform that task after deserialization. Do something like:

var company = //deserialized value

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

Or a one-liner, if you prefer the syntax:

company.employees.ForEach(e => e.employer = company);
like image 119
mattytommo Avatar answered Sep 29 '22 03:09

mattytommo