Reputation: 759
I got a json Object that i want to deserialize to its .Net type without casting it.
I think i read somewhere in the doc that you can pass an attribute into the json to tells to the deserializer the .Net object type that it can try to cast.
I can't find the where i read this.
I want to avoid use of
var myNewObject = JsonConvert.DeserializeObject<MyClass>(json);
To get something like this
MyClass myNewObject = JsonConvert.DeserializeObject(json);
I got my json object from an HttpRequest and want to instantiate the appropriate class from this nested object. Currently deserialization into an known item work good but need something more flexible without the need to manage all known Object from a parsing method.
Upvotes: 4
Views: 3196
Reputation: 4170
You can save the object type in your json string like this.
The settings you have to hand over the converter
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
};
How to serialize with the given settings:
var json = JsonConvert.SerializeObject(data, Settings);
This is what your json string looks like:
{
"$type":"YourNamespaceOfTheClass",
"YourPropertyInTheClass":valueOfProperty
}
How to deserialize with the given settings:
var object = JsonConvert.DeserializeObject(json, Settings);
Now your json string contains not only the serialized object, but also the type of your serialized object. So you don't have to worry about the right type when deserializing your json string.
Upvotes: 6
Reputation: 2129
You can do something like this:
var result = JsonConvert.DeserializeObject<dynamic>(json);
so you can deserialize any object. Cast dynamic says that you're deserializing an anynymous object with any type which will be known on runtime. It trully works!
Upvotes: 0
Reputation: 34189
You can do the following:
dynamic myNewObject = JsonConvert.DeserializeObject(json);
which will return a dynamic object which you can work with.
Console.WriteLine(myNewObject.data[0].description);
Obviously, it will fail if your JSON doesn't contain data
array having objects with description
property.
Upvotes: 2