【问题标题】:Deserialize different json files using the same class使用同一个类反序列化不同的json文件
【发布时间】:2018-08-16 06:45:50
【问题描述】:

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

数据部分不同。

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

【问题讨论】:

  • 不,你不能。可能使用字典而不是Expando
  • @Rahul,expando 是什么?
  • @Alexan Rahul 指的是to this by Expando

标签: c# json json.net


【解决方案1】:

在两个 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多