【问题标题】:Deserialize certain JSON properties into subclass将某些 JSON 属性反序列化为子类
【发布时间】:2011-12-28 13:10:33
【问题描述】:
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&lt;T&gt; 处于同一级别,但我想将它们包装到ApiError 类中,我该如何做到这一点?

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

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

我想有一些属性可以让我很容易地完成这项工作,但我无法弄清楚该配置应该是什么。

【问题讨论】:

    标签: c# json serialization


    【解决方案1】:

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

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

    免责声明:我只使用 JavaScriptSerializer 类创建 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属性会被序列化。

    【讨论】:

    • 我知道,我可以用[JsonIgnore] 做到这一点,但我想将这三个序列化到子类中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 2012-08-19
    相关资源
    最近更新 更多