首页 > 解决方案 > Unity.FromJason 解析时无效值

问题描述

当试图从 Json 中反序列化数据时,我得到一个无效的值错误。为了进行实验,我减少了键/值的数量。我尽力找到解决方案,但我从未使用过 json。

  {"id": 2} //all code inside my json

public class Weapon
{public int id;}

Debug.Log(JsonUtility.FromJson<Weapon>("/Resources/db/wargear.json"));


ArgumentException: JSON parse error: Invalid value.

标签: c#jsonunity3d

解决方案


您尝试解析的 JSON 是文字路径"/Resources/db/wargear.json"

您必须首先将 JSON 文件作为文本资产加载,并将其中的文本传递给 JSON 反序列化器函数。

public class Weapon
{
    public int id;
}

void Start()
{
    var textAsset = Resources.Load<TextAsset>("db/wargear.json");
    var weapon = JsonUtility.FromJson<Weapon>(textAsset.text);
    Debug.Log(weapon.id);
}

推荐阅读