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.
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With