views:

223

answers:

1

Consider the following JSON:

{
    "Code": 2, 
    "Body": {
        "Dynamic-Key": {
            "Key1": "Val1", 
            "Key2": "Val2"
        }
    }
}

Defining the following classes structure:

[DataContract]
class JsonResponse
{
    [DataMember]
    public string  Code { get; set; }
    [DataMember]
    public JsonResponseBody Body { get; set; }
}
[DataContract]
class JsonResponseBody
{
    [DataMember(Name = "Dynamic-Key")]
    public DynamicKeyData Data { get; set; }
}
[DataContract]
class DynamicKeyData
{
    [DataMember]
    public string Key1 { get; set; }
    [DataMember]
    public string Key2 { get; set; }
}

I can deserialize the given JSON with the following code:

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(JsonResponse));
JsonResponse responseData = serializer.ReadObject(responseStream) as JsonResponse;

However in my case the "Dynamic-Key" is not known and is defined by user input value. What is the right way to handle this kind of JSON definition?

Considerations:

The JSON is of a third party Api, so changing it is not an option.

In my case I don't care about the Dynamic-Key name, so if there is an option to always map to one generic name it will do the job.

Thanks in advance.

+2  A: 

Do you definitely need to use WCF? Otherwise I'd recommend looking at Json.NET. There's a number of extensibility mechanisms such as Contract Resolvers (I can't link to the Contract Resolvers page as I don't have enough reputation, apparently!)

Tim