4

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.

katronai
  • 540
  • 1
  • 8
  • 25
Leze
  • 739
  • 5
  • 24

3 Answers3

6

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.

croxy
  • 4,082
  • 9
  • 28
  • 46
  • 1
    It's exactly what i was looking for. Thanks – Leze Dec 15 '15 at 11:20
  • and if i want to deserialize an object that it's inside another jsonObject. Ex: i got an jsonObject like : `{"$type":"ServerResponse","message":"text","error":"error","result":[{"$type":"fooClass","message":"message"}]}` – Leze Dec 15 '15 at 20:36
  • Will something like this work for you: `dynamic myObject = JsonConvert.DeserializeObject(json, Settings);` an then `var insideObject = myObject.result` ? Or have it to be more flexible? Because at the moment I can't think of another way doing this. – croxy Dec 16 '15 at 07:55
2

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.

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
0

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!

Anton23
  • 2,079
  • 5
  • 15
  • 28