Search code examples
c#jsonjson-deserialization

Deserializing Some Odd JSON using C#


I have a JSON document coming from a vendor that looks like this:

{
    "content": [{
        "name": "Windows 8.1 x64",
        "id": "Windows81x64",
        "components": {
            "Windows81x64": {
                "propertyGroups": ["VirtualWindows81x64"],
                "dependsOn": [],
                "data": {
                    "provisioning_workflow": {
                        "fixed": {
                            "id": "WIMImageWorkflow",
                            "label": "WIMImageWorkflow"
                        }
                    },
                    "memory": {
                        "default": 2048,
                        "min": 2048,
                        "max": 16384
                    }
                }
            }
        }
    }]
}

Most of this document is fairly easy to deserialize into an object using the typical DataContractSerializer, however, there are a couple of keys/values that I am not sure what the "best practice" might be.

If you look at the "components" key the first key after that one is titled "Windows81x64". This key can change from document to document and it can be any value. It almost should be a 'Name' property of the collection but I can't control that. Furthermore, inside the 'Windows81x64' key there is another property called 'data'. According to the vendor the value of data is 'anonymous.' So, basically it can be anything.

Any ideas on the best way to deserialize this into a custom object when it comes to those parts of the document? Thank you.


Solution

  • You can deserialize dynamic ones as Dictionary<string, object>

    Or if you know the value's type you can use Dictionary<string, ValueType> where the key of the dictionary would be the name (in your case Windows81x64)