从SreamingAssets文件夹中读取json文件

时间:2018-10-25 03:03:26

标签: c# json parsing unity3d

我对Unity的FromJson方法有疑问。从错误中,我假设我编写的JSON出了点问题,但我无法终生弄清楚它是什么。首先,这是错误

ArgumentException: JSON parse error: Invalid value.
UnityEngine.JsonUtility.FromJson[ShipTypes] (System.String json) (at C:/buildslave/unity/build/artifacts/generated/bindings_old/common/JSONSerialize/JsonUtilityBindings.gen.cs:25)
DataLoader.LoadShipsFromJSON () (at Assets/Scripts/Data/DataLoader.cs:38)
DataLoader.Awake () (at Assets/Scripts/Data/DataLoader.cs:19)

接下来,代码(最后一行是Dataloader.cs:38)

ShipTypes shipTypes;
string path = Application.streamingAssetsPath + "/ShipTypes.json";
shipTypes = JsonUtility.FromJson<ShipTypes>(path);

这是我的课程

[System.Serializable]
public class ShipTypes
{
    public List<Ship> ships;
}

[System.Serializable]
public class Ship
{
    public string name;
    public int attack;
    public int defense;
    public int speed;
    public int range;
}

最后这是我的JSON

{
  "ships" : 
    [
        {
            "name": "Corvette",
            "attack" : 2,
            "defense" : 7,
            "speed" : 20,
            "range" : 8
        },
        {
            "name": "Frigate",
            "attack" : 4,
            "defense" : 6,
            "speed" : 10,
            "range" : 8
        },
        {
            "name": "Destroyer",
            "attack" : 8,
            "defense" : 8,
            "speed" : 10,
            "range" : 8
        },
        {
            "name": "Dreadnought",
            "attack" : 14,
            "defense" : 10,
            "speed" : 7,
            "range" : 8
        },
        {
            "name": "Battleship",
            "attack" : 20,
            "defense" : 12,
            "speed" : 5,
            "range" : 8
        }
    ]
}

非常感谢您。

2 个答案:

答案 0 :(得分:2)

解决方法是加载内容,调用需要JSON文本,而不是文件路径:

ShipTypes shipTypes;
string path = Application.streamingAssetsPath + "/ShipTypes.json";
string contents = File.ReadAllText(path);
shipTypes = JsonUtility.FromJson<ShipTypes>(contents);

答案 1 :(得分:1)

对于以下方法,您应该提供JSON内容而不是JSON文件的路径→

JsonUtility.FromJson<T>(json_content_in_string);

因此建议您先阅读内容

string path_to_json  = Application.streamingAssetsPath + "/ShipTypes.json";
string json_contents = File.ReadAllText(path_to_json);

然后转换

shipTypes = JsonUtility.FromJson<ShipTypes>(json_contents);