使用JsonUtility在Unity中寫入json數據

1.在Asset目錄中新建一個腳本,命名爲StudentItem,寫入以下代碼

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class StudentItem
{
    public int id;
    public string name;
    public float score;

    public StudentItem(int _id, string _name, float _score)
    {
        id = _id;
        name = _name;
        score = _score;
    }
}

2.在Asset目錄中新建一個腳本,命名爲JsonCreator,寫入以下代碼

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class JsonCreator : MonoBehaviour
{
    List<StudentItem> list = new List<StudentItem>();

	void Start ()
    {
        //如果Asset目錄下的StudentData.json文件不存在,則創建一個這樣的文件
        if (!File.Exists(Application.dataPath + "/StudentData.json"))
        {
            File.CreateText(Application.dataPath + "/StudentData.json");
        }
        StudentItem student1 = new StudentItem(10001, "張三", 80f);
        StudentItem student2 = new StudentItem(10002, "李四", 60f);
        list.Add(student1);
        list.Add(student2);
        //寫入數據
        string jsonData = "{\"student\":[\n";
        for (int i = 0; i < list.Count; i++)
        {
            if (i == list.Count - 1)
            {
                jsonData += JsonUtility.ToJson(list[i]) + "\n";
                break;
            }
            jsonData += JsonUtility.ToJson(list[i]) + "\n,";
        }
        jsonData += "]}";
        StreamWriter sw = new StreamWriter(Application.dataPath + "/StudentData.json");
        sw.WriteLine(jsonData);
        //注意寫入數據以後關閉
        sw.Close();
	}
}

3.運行Unity,我們發現Asset目錄下的StudentData.json文件已經寫入完成

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章