Load an irregular array from json

I’m trying to write a dnd help software and have downloaded a database of all the creatures for it.
But i have a problem assigning a array.
The array looks like this
"ac": [ 12, { "ac": 15, "condition": "with {@spell mage armor}", "braces": true } ],
But I don’t know how to assign a variable to this array.
I have tried using a int at first but that only returned a {12, 0}
And I have tried a custom class [System.Serializable] public class ArmorClass{ public int ac; public string condition; public bool braces; }
This way i get the output inside the brackets but then I don’t get the first number (12)
If you have any idea for how to do this I would be very greatfull.

Most json serializers are object mappers and they usually can’t handle mixed type arrays properly. Since the array uses different element types, you could try using an object[] array. However that would not work with Unity’s JsonUtility, you would need at least something like the Newtonsoft Json.NET library.

Instead of object mapping you can also use a parser like my SimpleJSON. It just parses the json into destinct json classes for each type that json can represent (JSONObject, JSONArray, JSONString, JSONNumber, JSONBool, JSONNull). It’s designed to just give easy access to the parsed data without the need to manually cast or convert the types. Note that this is not an object mapper, at all. So it can not automatically initialize your own custom types. However it’s designed with extensibility in mind. You can easily add custom conversion of a JSONObject from / to your own type. The repository has a couple of “extension” files. One specifically for Unity to support some Unity types out of the box like Vectors.

You’ve only shown fragments of your json, so it’s hard to give you a concrete usecase. Though assuming the json looks something like this:

{
    "ac" : [
        12,
        {
            "ac" : 15,
            "condition" : "with {@spell mage armor}",
            "braces": true
        }
    ]
}

you can parse it and use it like this:

var node = JSON.Parse(yourJsonText);
int ac = node["ac"][0];
string condition = node["ac"][1]["condition"];
bool braces = node["ac"][1]["braces"];

Since you only showed fragments of your json, it’s up to you to make sense of the data it contains. The framework can parse any valid json, even those which usually can’t object mapped (like keys starting with numeric values or contain spaces).

Internally the JSONArray contains a List of JSONNodes while a JSONObject contains a Dictionary of nodes. You can also use this to easily build json

JSONNode n = new JSONObject();
n["someKey"]["subkey"] = 42;
n["someKey"]["name"] = "foobar";
string json = n.ToString(); // returns {"someKey": {"subkey" : 42, "name" : "foobar"}}

The ToString method can also take an increment to format the output with that many spaces per level.