使用动态属性名称反序列化通用嵌套类型

我得到下面的JSON对象作为响应:

{
    status: false,employee: {
        firstName: "Test",lastName: "Test_Last"
    }
}

由于上述字符串是API响应,因此“ Employee”是动态属性。可以是用户或公司等。

因此,要在C#中反序列化上述对象,我创建了一个类似以下的类结构:

public class Response<T> {

    [JsonProperty(PropertyName = "status")]
    public bool Status {get;set;}

    public T Item {get;set;}

}

[JsonObject(Title = "employee")]
public class Employee {

    [JsonProperty(PropertyName = "firstName")]
    public string FirstName {get; set;}

    [JsonProperty(PropertyName = "lastName")]
    public string LastName {get; set;}

}

但是当我尝试反序列化JSON字符串时,Employee类不会反序列化,而employee对象的值始终保持为null。

这是我反序列化JSON字符串的方式:

Newtonsoft.Json.JsonConvert.DeserializeObject<Response<Employee>>(jsonString);

我相信我对Employee类的JsonObject属性做错了。但是我不确定。

anwencpu 回答:使用动态属性名称反序列化通用嵌套类型

假设如示例OP代码中所示,为预期类型设置了JObjectAttribute,则可以使用Custom DefaultContractResolver。例如,

public class GenericContractResolver<T> : DefaultContractResolver  
{

    protected override JsonProperty CreateProperty(MemberInfo member,MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member,memberSerialization);
        if (property.UnderlyingName == nameof(Response<T>.Item))
        {
            foreach( var attribute in System.Attribute.GetCustomAttributes(typeof(T)))
            {
                if(attribute is JsonObjectAttribute jobject)
                {
                    property.PropertyName = jobject.Title;
                }
            }
        }
        return property;
    }
}

用法

var result = JsonConvert.DeserializeObject<Response<Employee>>(json,new JsonSerializerSettings 
                                           { 
                                             ContractResolver = new GenericContractResolver<Employee>() 
                                           });

Demo Code

,

我肯定会采用 ContractResolver 的方式。当您需要专门的序列化时,它们会有所帮助。这是 Brian Oliver 撰写的一篇文章,解释了如何使用它们。他的示例非常接近您可能正在寻找的内容。 https://www.c2experience.com/blog/using-custom-contract-resolvers-for-jsonnet

本文链接:https://www.f2er.com/2989205.html

大家都在问