将某些JSON属性反序列化为子类 [英] Deserialize certain JSON properties into subclass

查看:743
本文介绍了将某些JSON属性反序列化为子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class ApiResponse<T> : IApiResponse<T>
{
    public long QuotaRemaining { get; set; }
    public long QuotaMax { get; set; }
    public int Backoff { get; set; }
    public bool HasMore { get; set; }
    public long Total { get; set; }
    public string Type { get; set; }
    //public long ErrorId { get; set; }
    //public string ErrorMessage { get; set; }
    //public string ErrorName { get; set; }
    public IList<T> Items { get; set; }

    public ApiError Error { get; set; }
}

public class ApiError
{   
    [JsonProperty("error_id")]
    public long ErrorId { get; set; }

    [JsonProperty("error_message")]
    public string ErrorMessage { get; set; }

    [JsonProperty("error_name")]
    public string ErrorName { get; set; }
}

Error属性实际上与ApiResponse<T>处于同一级别,但是我想将它们包装到ApiError类中,我该如何完成呢?

Thing is the Error properties are actually at the same level as ApiResponse<T>, but I'd like to wrap them into an ApiError class, how could I accomplish this?

我目前正在这样反序列化:

I'm currently deserializing like this:

    public static T DeserializeJson<T>(this string json)
    {
        return JsonConvert.DeserializeObject<T>(json);
    }

我想有一些属性可以让我轻松完成此操作,但我无法弄清楚该配置应该是什么.

I guess there's some set of attributes that allows me to accomplish this pretty easily, but I can't figure out what that configuration should be.

推荐答案

您可以通过装饰属性来选择要序列化的属性.

You can pick and choose which properties are serialized by decorating them.

添加[ScriptIgnore]将导致该属性不被序列化.这实际上并没有创建子类,但确实提供了一种仅序列化所选属性的方法.

Adding [ScriptIgnore] will cause the property to not be serialized. This doesn't really create a subclass, but does provide a way to only serialize selected properties.

免责声明:我只使用JavaScriptSerializer类创建JSON.

Disclaimer: I have only ever done this using the JavaScriptSerializer class to create the JSON.

示例:

public class ApiResponse<T> : IApiResponse<T>
{
    [ScriptIgnore]
    public long QuotaRemaining { get; set; }
    [ScriptIgnore]
    public long QuotaMax { get; set; }
    public int Backoff { get; set; }
    public bool HasMore { get; set; }
}

在上面的类中,只有BackoffHasMore属性将被序列化.

In the above class, only the Backoff and HasMore properties will be serialized.

这篇关于将某些JSON属性反序列化为子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆