简体   繁体   English

创建用于JSON反序列化的类

[英]Creating a class for JSON deserialization

Consider the following JSON: 考虑以下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: 我可以使用以下代码反序列化给定的JSON:

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? 处理这种JSON定义的正确方法是什么?

Considerations: 注意事项:

The JSON is of a third party Api, so changing it is not an option. JSON是第三方Api的,因此无法更改。

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? 您肯定需要使用WCF吗? Otherwise I'd recommend looking at Json.NET . 否则,我建议您查看Json.NET There's a number of extensibility mechanisms such as Contract Resolvers 有很多扩展机制,例如合同解析器

Store the JSON in a string let suppose in strResult. 将JSON存储在假设在strResult中的字符串中。 Then you can deserialize it into the JsonResponse object as follows: 然后,可以按如下所示将其反序列化为JsonResponse对象:

JsonConvert is the class in Newtonsoft.Json.JsonConvert dll. JsonConvert是Newtonsoft.Json.JsonConvert dll中的类。 You can use it as follows: 您可以按以下方式使用它:

JsonResponse object= (JsonResponse)JsonConvert.DeserializeObject(strResult,  typeof(JsonResponse));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM