I have somewhat deep Json structure like below incoming over the wire into C# application: :
[
{
"status": "ok",
"node": "vm2",
"type": "message",
"result": {
"tx.mqid": "amq.gen-+Phq5acfC9kbs7Ch/0cUUw==",
"tx.time": 1297273910,
"tx.id": 28
}
}
...
]
I’m doing deserialization like this:
List<Hashtable> des = JsonConvert.DeserializeObject<List<Hashtable>>(objs);
Now, I need to extract “result” dictionary from the structure above.
The problem with doing it is that it’s not always there. It may be replaced with something else, esp. when error happens. Also, result may change depending on what function was called by Json client. So I can’t really specify it in static fashion like this:
JsonConvert.DeserializeObject<List<Hashtable<Hashtable>>>
For now I’m doing deserialization in somewhat boneheaded manner, like this:
JObject nodeResult = (JObject)nodeRec["result"];
Hashtable nrh = JsonConvert.DeserializeObject<Hashtable>(nodeResult.ToString());
That is, I’m deserializing “result” into JObject, then serializing it into text, and then deserializing it into Hashtable.
Is there any way to convert JObject directly into Hashtable, or make structures nested deeply in the json text like “result” into Hashtable to begin with? The above approach works, but I hate its clunkiness.
what you want to do is deserialize to an object that represents the json.
and then update your deserialize code to this
it can be a bit finnicky about the naming and ordering / nesting of things so be careful.