Reputation: 2236
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.
Upvotes: 1
Views: 1161
Reputation: 1786
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
Upvotes: 3
Reputation: 3462
Store the JSON in a string let suppose in strResult. Then you can deserialize it into the JsonResponse object as follows:
JsonConvert is the class in Newtonsoft.Json.JsonConvert dll. You can use it as follows:
JsonResponse object= (JsonResponse)JsonConvert.DeserializeObject(strResult, typeof(JsonResponse));
Upvotes: 0