Reputation: 992
i'm trying to deserialize some JSON into objects it works perfectly .. almost ...
i'm using the NewtonSoft.Json lib in C#
i have a serie of nested classes.
For example:
class car (string prop, string prop2}
within the car class a nested class wheel
class wheel {string prop, car Parent}
now i want to get a reference from the wheel class to the car (Parent) class the DeserializeObject works good, is deserializing all the object and nested objects
Car c = JsonConvert.DeserializeObject<Car>(jsonString);
but it seems impossible to get a reference the parent class :( ?
Upvotes: 1
Views: 2593
Reputation: 27811
You can set this property on both ends (client/server) and Json.net should link the tree back together during deserialization:
JsonSerializerSettings settings = new JsonSerializerSettings {
PreserveReferencesHandling = PreserveReferencesHandling.All
};
You can pass those settings into each call to JsonConvert.SerializeObject
, or you can set them globally using:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.All;
Upvotes: 0
Reputation: 992
fixed!
{
"$id":"1",
"id":"car1",
"name":"test",
"description":"nice car",
"wheel":[
{
"car":{"$ref":"1"},
"name":"section",
"description":"nice car"
}
]
}
just added $ref
in the JSON
Upvotes: 2
Reputation: 1456
Instead of serializing and deserializing the Car object. In you scenario, you can actually serialize and deserialize the Wheel object. In doing so, you will have the both the car and the wheel's information.
Try to deserialize the Json to Wheel object.
Upvotes: 0