Alexan
Alexan

Reputation: 8637

Deserialize different json files using the same class

I use the following class to deserialize 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 }
            },
        };
    }

It works fine with the following 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  
}

And deserialized to the following class:

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

But I want to deserialize the following json:

{
  "data": [
    "Science",
    "Political",
    "News"
  ],
  "success": true  
}

Data part is different.

Can I use the same class for deserializing both?

Upvotes: 1

Views: 222

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32063

In both JSONs, data and success are part of an object, so you can use a generic wrapper:

public class Wrapper<T> 
{
    // No need for [JsonProperty("data")] here
    public T[] Data { get; set; }
    public bool Success { get; set; }
}

And then you just need to specify T when de/serializing:

string json = "...";
var wrappedSuscribers = JsonConvert.DeserializeObject<Wrapper<Suscriber>>(json);
//OR
var wrappedSomething = JsonConvert.DeserializeObject<Wrapper<string>>(json);

Upvotes: 3

Related Questions