我使用以下类反序列化json:
public class Welcome
{
[JsonProperty("data")]
public Subscriber[] Data { get; set; }
[JsonProperty("success")]
public bool Success { get; set; }
public static Welcome FromJson(string json) => JsonConvert.DeserializeObject<Welcome>(json, Settings);
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters = {
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
它可以与以下json一起正常工作:
{
"data": [
{
"id": "04f8ab66-a44a-4918-a938-2d73f193b031",
"firstName": "Autumn",
"lastName": "Alexander",
"magazineIds": [
5,
8,
7,
2,
9
]
},
{
"id": "63da0606-9b5a-4ac9-923b-f70045e95735",
"firstName": "Rebecca",
"lastName": "Parker",
"magazineIds": [
5,
8,
1
]
},
],
"success": true
}
并反序列化为以下类:
public class Subscriber
{
[JsonProperty("id")]
public Guid Id { get; set; }
[JsonProperty("firstName")]
public string FirstName { get; set; }
[JsonProperty("lastName")]
public string LastName { get; set; }
[JsonProperty("magazineIds")]
public long[] MagazineIds { get; set; }
}
但是我想反序列化以下json:
{
"data": [
"Science",
"Political",
"News"
],
"success": true
}
数据部分不同。
我可以使用同一类反序列化这两个吗?
答案 0 :(得分:3)
在两种JSON中,data
和success
都是对象的一部分,因此您可以使用通用包装器:
public class Wrapper<T>
{
// No need for [JsonProperty("data")] here
public T[] Data { get; set; }
public bool Success { get; set; }
}
然后在解序列化时只需指定T
:
string json = "...";
var wrappedSuscribers = JsonConvert.DeserializeObject<Wrapper<Suscriber>>(json);
//OR
var wrappedSomething = JsonConvert.DeserializeObject<Wrapper<string>>(json);