使用相同的类反序列化不同的json文件

时间:2018-08-15 22:37:59

标签: c# json json.net

我使用以下类反序列化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  
}

数据部分不同。

我可以使用同一类反序列化这两个吗?

1 个答案:

答案 0 :(得分:3)

在两种JSON中,datasuccess都是对象的一部分,因此您可以使用通用包装器:

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