Question

I am using Newtonsoft.Json.JsonConvert.DeserializeObject(string str) to translate a string into a .Net Object. The real type of this string can be multiple, and there's no other information to indicate the type of this string. But I can confirm that the string message is a derived class object of a common class like Message, and fields in Message can however tell the real type, Message has a field like int type. The string is MessageA or MessageB or whatever all with a different type.

If I translate it into an Object, I can saw in the visual studio debugger that this Object have exactly the fields described in the Json string. But I cant access these fields. And cast this Object into a Message will failed with a bad cast.

What I am doing now is first translate the string into a Message and to see the type, then I translate again. It's not preferred. So can I just translate it into something that I can read all of the data? Another option is Dictionary, but I have some numerical fields. Any other suggestions?

Was it helpful?

Solution

JsonConvert.DeserializeObject(string str), when used on a JSON object, returns a JObject. You can use this directly (e.g. use DeserializeObject<JObject> to explicitly type it), or as a dynamic, to access its properties, e.g.

var data = @"{""type"": 1, ""otherProperty"": ""Hello!""}";
dynamic obj = JsonConvert.DeserializeObject(data);
if (obj.type == 1)
{
    Console.WriteLine(obj.otherProperty); // prints Hello!
}

Also, you mention numeric fields as being a problem with working with a dictionary, but if you make it a Dictionary<string, dynamic> you might find it easier to work with:

var data = @"{""type"": 2, ""otherProperty"": 5}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(data);
if (dict["type"] == 2)
{
    int i = (int)dict["otherProperty"]; // type is long, so cast is required if you want an int
    Console.WriteLine(i); // prints 5
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top