0

I have this method that returns an array from JSON

public static T[] FromJson<T>(string json)
{
    Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
    return wrapper.Items;
}

And the Wrapper class:

[Serializable]
private class Wrapper<T>
{
    public T[] Items;
}

This is the JSON file structure:

{
"Tiles":
[
    {
        "id": "air",
        "name": "Air",
        "itemID": "air",
        "texture": {
            "x": 0.0,
            "y": 0.0
        },
        "properties": {
            "hardness": 0,
            "undestructible": true
        }
    },
    ...
]
}

And this Tile class:

[Serializable]
public class Tile {
    public string id;
    public string name;
    public string itemID;
    public Vector2 texture;
    public Properties properties;
}

[Serializable]
public class Properties {
    public double hardness = 0;
    public bool undestructible = false;
}

When I run the FromJson method it returns null for the Tile class but for the following JSON structure it works:

{
"Items":
[
    {
        "id": "dirt",
        "name": "Dirt",
        "description": "Just some dirt.. might be useful some day."
    },
    ...
]
}
Teodor Vecerdi
  • 198
  • 1
  • 1
  • 12
  • Isn't it clear. Your json doesn't have a *Items* property. So you get null. – Eser May 04 '18 at 19:34
  • @Eser I have an Item class that has the fields id, name and description and that works. With the tile class and tile json it doesn't work – Teodor Vecerdi May 04 '18 at 19:35
  • **Your json doesn't have a *Items* property** – Eser May 04 '18 at 19:36
  • @Eser oh I understood now what you mean. Thanks! – Teodor Vecerdi May 04 '18 at 19:39
  • Paste your json [here](http://json2csharp.com/) to generate the correct structure for it. The duplicate should help you de-serialize that json. If you still run into issues, see the troubleshooting sections that shows why it might return null. Note: Do not name your class `Tile` or `Texture`. Your json contains these and there are Unity API with the-same names. You'll likely run into issues with this. – Programmer May 04 '18 at 19:44
  • @Programmer thanks for the suggestion. Regarding naming the class `Tile` it won't affect me since I don't use Unity's Tile class but I know that in general it's not ok to do this :D – Teodor Vecerdi May 04 '18 at 19:57
  • 1
    It doesn't matter if you are using it or not. As long as the namespace (`UnityEngine.Tilemaps`) is imported, you are bound to run into issues sooner or later. As for `Texture`, that's already imported since you are using API from `UnityEngine`. I saw a person that ran into this issue weeks ago which made `GetComponent` to return the wrong class. It's just a heads up for you. – Programmer May 04 '18 at 20:02

0 Answers0