0

How can i unserialize a list of different objects uwing JSON.net?

string myJson = "[{action: 'a1', target: 4},{action: 'a2', targets: [1,2,3], {action:'a3', text:'targets altered'}}]";

This example presents a list of 3 different objects. If I unserialize as a basic Object, I cannot access any members (as the base Object class doesn't have them).

I've looked over http://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm but I don't understand if it can help me.

Quamis
  • 10,924
  • 12
  • 50
  • 66
  • TypeNameHandling is used to embed the type information when serializing to JSON. That type information is then used during deserialization. If your JSON comes from an external source it won't have that type information, so it's not suitable for what you want. –  Feb 11 '16 at 16:38
  • Take a look at [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/questions/19307752). – dbc Feb 11 '16 at 16:57

2 Answers2

0

Use the dynamic type. You can access elements as if they were properties. If a property doesn't exist, the dynamic type will return null instead of throwing an exception

dynamic actions = JsonConvert.DeserializeObject(myJson);
foreach (var action in actions)
{
    var name = action.action.ToString();
    var target = action.target.ToString();
    var text = action.text.ToString();
    if (target == null)
    {
         dynamic targets = action.targets;
    }
}
Amadeusz Wieczorek
  • 3,139
  • 2
  • 28
  • 32
0

with that method you posted, your json should contain extra info to indicate what type it is,which means you need to modify how the source of json to serialize,and make sure the you use the same class,namespace as the source serialized.

Or,use Object or dynamic as type of target, and to convert it in later use may be easier.

kiro
  • 111
  • 1
  • 4
  • How can I convert it? Using the dynamic approach seems to work, but this way I loose the advantages of autocompletein the IDE, and self-validation (I'd like to validate and add some custom functions for each action type). Simply typecasting doens't work, and using `Convert.ChangeType` throw an error about IConvertible – Quamis Feb 12 '16 at 07:15
  • To convert type, i think is another problem. ToValidate the class, the alternative is make you class inherit DynamicObject,like example in [MSDN Example](https://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.tryconvert(v=vs.110).aspx). You can override `TryConvert` to convert the type you want. There also are lots of article or lib using reflection to convert dynamic to class – kiro Feb 12 '16 at 07:48
  • In the end I've relied on using the hints from https://stackoverflow.com/questions/19307752/deserializing-polymorphic-json-classes-without-type-information-using-json-net. Basically I'm using a custom de-serializer for JSON.net, and handle each type differently – Quamis Feb 12 '16 at 09:03