Search code examples
c#jsondynamicdeserializationcomplextype

Deserialize a complex dynamic JSON string


What if the object to deserialize looked like this (where the keys Ioc, Name, id and timestamp are static, and the fields key is dynamic - meaning that it may contain a variable amount of items)???

{
   "moduleinstances": [
     {
        "Ioc": "ioc1", 
        "Name": "name1", 
        "fields": {
            "PV_PREFIX": "PIPE", 
            "TIMEOUT": "1"
        }, 
        "id": 25, 
        "timestamp": "/Date(1393518678000)/"
     }
    ]
}

How to deserialize this kind of strings?


Solution

  • The secret is to keep your deserialized JSON in the most general form possible:

    Dictionary<string, object> theData= new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(jsonString);
    
    Dictionary<string, object> fieldsNode = (Dictionary<string, object>)theData["fields"];
    
    string pv_prefix = (string)fieldsNode["PV_PREFIX"];
    string timeout = (string)fieldsNode["TIMEOUT"];
    

    The call to Deserialize() creates a tree of Dictionary<string, object> that you can traverse at will.