问题
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