JsonUtility

[System.Serializable]
public class Student
{
    public string name;
    public int age;
    public Student(int age,string name)
    {
        this.age = age;
        this.name = name;
    }
}
public class Robot
{
    public string name = "robot";
    public int age = 5;
    public bool gender = true;
    public int[] ids;
    public List<int> ids2;
    public Dictionary<int, string> dic;
    public Student s1;
    [SerializeField]
    private float f = 1.4f;
}
public class L1 : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //jsonUtility用于序列化和反序列化json

        //1.存储字符串到指定路径中
        //文件夹路径必须存在
        File.WriteAllText(Application.persistentDataPath + "/Test.json", "存储的字符串");
        print(Application.persistentDataPath);

        //2.在指定路径文件中读取字符串
        string str = File.ReadAllText(Application.persistentDataPath + "/Test.json");
        print(str);

        //使用Utility进行序列化
        //JsonUtility.ToJson(对象);
        Robot robot = new Robot();
        robot.ids = new int[]{1, 2, 4};
        robot.ids2 = new List<int>() { 1,2,3};
        robot.dic = new Dictionary<int, string>() { { 1, "123" } ,{2,"234"}};
        robot.s1 = new Student(1,"bobo");
        string jsonStr = JsonUtility.ToJson(robot);
        File.WriteAllText(Application.persistentDataPath + "/robot.json", jsonStr);
        //float类型的值在序列化时看起来会有一点误差,但是不影响读取使用
        //自定义类需要加上序列化特性[System.Serializable]
        //需要序列化的私有变量之前需要加上特性[SerializeField]
        //JsonUtility不支持字典
        //JsonUtility存储null对象时不会存null,而是会存储该类型的默认值

        //使用utility进行反序列化
        //JsonUtility.FromJson()
        jsonStr = File.ReadAllText(Application.persistentDataPath + "/robot.json");
        //把json转换为类对象
        //Robot robot2 =  JsonUtility.FromJson(jsonStr,typeof(Robot)) as Robot;
        Robot robot3 = JsonUtility.FromJson<Robot>(jsonStr);
        //jsonUtility无法直接读取数据集合,比如数组和list,需要在json数据集合外层包裹一个对象,并在脚本中也申明一个相应的数据结构类才能读取
        //文本编码格式必须是UTF-8
    }
}
posted @ 2025-04-06 11:58  cannedmint  阅读(22)  评论(0)    收藏  举报