Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize array within array

I just downloaded a huge JSON file with all current MTG sets/cards, and am looking to deserialize it all.

I've gotten most of each set deserialized, but I'm running into a snag when trying to deserialize the booster object within each Set:

enter image description here

enter image description here

As you can see from the above two pictures, in each booster object there is a list of strings, but for some booster objects there is also an additional array of more strings. Deserializing an array of exclusively strings isn't a problem. My issue arises when I run into those instances where there is an array of strings within the booster object that need deserializing.

Currently the property I have set up to handle this deserialization is:

public IEnumerable<string> booster { get; set; }

But when I run into those cases where there's another array within booster I get an exception thrown, where Newtonsoft.Json complains it doesn't know how to handle the deserialization.

So, my question then becomes: how can I go about deserializing an array of strings contained within an array of strings? And what would an object need to look like in C# code to handle that sort of deserialization?

like image 289
Delfino Avatar asked Nov 07 '22 11:11

Delfino


1 Answers

You could deserialize the per item as string[] even thought the item wouldn't be a collection. So, provide a custom serializer;

public class StringArrayConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JArray array = JArray.Load(reader);
        for (int i = 0; i < array.Count; i++)
        {
            //If item is just a string, convert it string collection
            if (array[i].Type == JTokenType.String)
            {
                array[i] = JToken.FromObject(new List<string> {array[i].ToObject<string>()});
            }
        }
        return array.ToObject<List<string[]>>();
    }

    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(List<string[]>));
    }
}
public class JsonObject
{
    [JsonConverter(typeof(StringArrayConverter))]
    public List<string[]> booster { get; set; }
}

Then deserialize the json;

var data = JsonConvert.DeserializeObject<JsonObject>(json);

Finally, you can deserialize a json like I provided below;

{
    "booster": [
      "1",
      "2",
          ["3","4"]
    ]
}
like image 190
lucky Avatar answered Nov 15 '22 06:11

lucky