首页 > 解决方案 > Unity JSON 解析返回 Null

问题描述

我有这个从 JSON 返回数组的方法

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

和包装类:

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

这是 JSON 文件结构:

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

而这个 Tile 类:

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

当我运行 FromJson 方法时,它为 Tile 类返回 null,但对于以下 JSON 结构,它可以工作:

{
"Items":
[
    {
        "id": "dirt",
        "name": "Dirt",
        "description": "Just some dirt.. might be useful some day."
    },
    ...
]
}

标签: c#jsonunity3d

解决方案


推荐阅读