Two ways to read Json file data

First download the LitJson.dll file and drag it into the Assets/Plugins directory in the Unity project

Secondly, create the Assets/StreamingAssets folder in your Unity project to store files

Function: write data into the file (freely expandable), and get the specified object when the program is running (here, get its object data according to the specified id).

The data parameters in the json file must be exactly the same as the field names disclosed in the Skill.

(Note that the permission of the Json file has a top-level item [ie an array or an object])

json skill information.text

[
  {
    "id": 1,
    "name": "D",
    "damage": 20
  },
  {
    "id": 2,
    "name": "T",
    "damage": 200
  },
  {
    "id": 3,
    "name": "C",
    "damage": 2000
  }
]

Corresponding Skill class data

public class Skill 
{
    public int id;
    public string name;
    public int damage;

}

code block:

private void OnGUI()
    {
        if (GUILayout.Button("读取方式一"))
        {
            string file = File.ReadAllText(Application.streamingAssetsPath +"/json技能信息.txt");
            //jsonData 代表一个数组或者一个对象【JsonData 就是json数据 根据json文件不同 其代表不用 ,可能为数组可能为对象】
            JsonData jsonData = JsonMapper.ToObject(file);
            Skill skill = new Skill();
            //使用 foreach 遍历 该数据
            foreach (JsonData temp in jsonData)//这里temp 代表一个对象
            {
                JsonData idValue = temp["id"];//通过字符串索引器 可以获得json文件中 键值对的值
                skill.id = int.Parse(idValue.ToString());

                skill.name = temp["name"].ToString();
                skill.damage = int.Parse(temp["damage"].ToString());
                //【将读取的数据对象】添加到字典集合中
                if (!skillDic.ContainsKey(skill.id))
                    skillDic.Add(skill.id, skill);
            }
            Debug.Log($"{skillDic[2].name},{skillDic[2].id},{skillDic[2].damage}");//C,3,2000
        }


        if (GUILayout.Button("读取方式二"))
        {
            string file = File.ReadAllText(Application.streamingAssetsPath + "/json技能信息.txt");
            //因为 json文件中 数据顶级项是数组 所以直接转换为 对象数组
            Skill[] skills = JsonMapper.ToObject<Skill[]>(file);
            
            //使用 foreach 遍历 该数据
            foreach (Skill temp in skills)//这里temp 代表一个对象
            {
                if (!skillDic.ContainsKey(temp.id))
                    skillDic.Add(temp.id, temp);//将数据添加到集合中
            }
            Debug.Log($"{skillDic[1].name},{skillDic[1].id},{skillDic[1].damage}");//D,1,20
        }

    }

Guess you like

Origin blog.csdn.net/weixin_44906202/article/details/128840303