开发者

Creating a class for JSON deserialization

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:

DataContra开发者_如何学GoctJsonSerializer 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.


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


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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜