Deserialize certain JSON properties into subclass

雨燕双飞 提交于 2019-12-24 23:20:06

问题


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; }
}

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.


回答1:


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

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.

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

Example:

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; }
}

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



来源:https://stackoverflow.com/questions/8656310/deserialize-certain-json-properties-into-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!