当前位置:   article > 正文

【Unity】数据持久化--JSON

【Unity】数据持久化--JSON

1、JSON基础语法

1.1 注释内容

单行注释 //

多行注释 /* 内容 */

  1. //注释内容
  2. /*
  3. 多行注释
  4. 123
  5. e1
  6. ds
  7. */
  8. /*

1.2 符号含义

大括号 {} 对象

中括号 [] 数组

冒号   : 键值对对应关系

逗号   , 数据分割

双引号 "" 键名/字符串

1.3 键值对表示

"键名":值内容

1.4 值类型

数字(整数或浮点)

字符串

true或false

数组

对象

null

  1. {
  2. "name":"小周",
  3. "age":24,
  4. "sex":true,
  5. "ids":[1, 2, 3],
  6. "students":[
  7. {"name":"小红", "age":18, "sex":false},
  8. {"name":"小明", "age":18, "sex":true}
  9. ],
  10. "home":{
  11. "address":"重庆市垫江县",
  12. "street":""
  13. },
  14. "son":{
  15. "name":"小周周",
  16. "age":7,
  17. "sex":true
  18. }
  19. }

2、JsonUtility

2.1 JsonUtility介绍

JsonUtility是Unity自带的用于解析Json的公共类

它可以将内存中对象序列化为Json格式的字符串,也可以将Json字符串反序列化为类对象

2.2 在文件中存读字符串

1) 存储字符串到指定路径文件中

File.WriteAllText(arg1, arg2)

第一个参数 填写的是存储的路径

第二个参数 填写的是 存储的字符串内容

2) 在指定路径文件中读取字符串

File.ReadAllText(path)

  1. //1.存储字符串到指定路径文件中
  2. //第一个参数 填写的是存储的路径!
  3. //第二个参数 填写的是 存储的字符串内容
  4. string path = Application.persistentDataPath + "/Test.json";
  5. File.WriteAllText(path, "大哥存储的JSON文件");
  6. Debug.Log(path);
  7. //2.在指定路径文件中读取字符串
  8. string str = File.ReadAllText(path);
  9. Debug.Log(str);

2.3 使用JsonUtlity进行序列化

序列化:把内存中的数据 存储到硬盘上

JsonUtility.ToJson(对象)

  1. [Serializable]
  2. public class Student
  3. {
  4. public int age;
  5. public string name;
  6. public Student(int age, string name)
  7. {
  8. this.age = age;
  9. this.name = name;
  10. }
  11. }
  12. public class MrTang
  13. {
  14. public string name;
  15. public int age;
  16. public bool sex;
  17. public float testFloat;
  18. public double testDouble;
  19. public int[] ids;
  20. public List<int> ids2;
  21. public Dictionary<int, string> dic;
  22. public Dictionary<string, string> dic2;
  23. public Student s1;
  24. public List<Student> s2s;
  25. }
  26. [Serializable]
  27. public class RoleInfo
  28. {
  29. public int hp;
  30. public int speed;
  31. public int volume;
  32. public string resName;
  33. public int scale;
  34. }
  35. //序列化:把内存中的数据 存储到硬盘上
  36. //方法:
  37. //JsonUtility.ToJson(对象)
  38. MrTang t = new MrTang();
  39. t.name = "小周";
  40. t.age = 18;
  41. t.sex = true;
  42. t.testFloat = 1.1f;
  43. t.testDouble = 1.5;
  44. t.ids = new int[] { 1, 2, 3 };
  45. t.ids2 = new List<int>() { 2, 3, 5, 6 };
  46. t.dic = new Dictionary<int, string>() {
  47. {1, "123" },
  48. {2, "234" }
  49. };
  50. t.dic2 = new Dictionary<string, string>() {
  51. {"12", "123" },
  52. {"sds", "234" }
  53. };
  54. t.s1 = new Student(18, "adada");
  55. t.s2s = new List<Student>() { new Student(12, "小红"), new Student(17, "小明") };
  56. //]sonutility提供了线程的方法 可以把类对象 序列化为 json字符串
  57. string jsonStr = JsonUtility.ToJson(t);
  58. File.WriteAllText(Application.persistentDataPath + "/MrTang.json", jsonStr);

注意:

  • float序列化时看起来会有一些误差
  • 自定义类需要加上序列化特性[system.serializable]
  • 想要序列化私有变量 需要加上特性[serializeField]
  • JsonUtility不支持字典
  • Jsonutlity存储nu11对象不会是nu11 而是默认值的数据

2.4 使用JsonUtility进行反序列化

反序列化:把硬盘上的数据 读取到内存中

JsonUtility.FremJson(字符串)

  1. //读取文件中的 Json字符串
  2. jsonStr = File.ReadAllText(Application.persistentDataPath + "/MrTang.json");
  3. //使用Json字符串内容 转换成类对象
  4. MrTang t2 = JsonUtility.FromJson(jsonStr, typeof(MrTang)) as MrTang;
  5. MrTang t3 = JsonUtility.FromJson<MrTang>(jsonStr);

注意:

  • 如果Json中数据少了,读取到内存中类对象中时不会报错

2.5 注意事项

  • 自定义尖需变加上序列化特性[System.serializable]
  • 私有保护成员 需要加上[SerializeField]
  • JsonUtility无法直接渎取数据集合
  • 文本编码格式需要时UTF-8 不然无法加载

3、LitJson

3.1 LitJson是什么

  • 它是一个第三方库,用于处理1son的序列化和反序列化
  • LitJson是c#编写的,体积小、速度快、易于使用
  • 它可以很容易的嵌入到我们的代码中
  • 只需要将LitJson代码拷贝到工程中即可

3.2 获取LitJson

  • 前往LitJson官网
  • 通过官网前往GitHub获取最新版本代码
  • 讲代码拷贝到unity工程中 即可开始使用LitJson

3.3 使用LitJson进行序列化

JsonMapper.ToJson(对象)

  1. //JsonMapper.ToJson(对象)
  2. MrTang2 t = new MrTang2();
  3. t.name = "下周";
  4. t.age = 18;
  5. t.sex = true;
  6. t.testFloat = 1.55f;
  7. t.testDouble = 1.4;
  8. t.ids = new int[] { 1, 2, 3 };
  9. t.ids2 = new List<int>() { 2, 3, 5, 6 };
  10. //t.dic = new Dictionary<int, string>() {
  11. // {1, "123" },
  12. // {2, "234" }
  13. //};
  14. t.dic2 = new Dictionary<string, string>() {
  15. {"12", "123" },
  16. {"sds", "234" }
  17. };
  18. //t.s1 = new Student2(18, "adada");
  19. t.s1 = null;
  20. t.s2s = new List<Student2>() { new Student2(12, "小红"), new Student2(17, "小明") };
  21. string jsonStr = JsonMapper.ToJson(t);
  22. Debug.Log(Application.persistentDataPath);
  23. File.WriteAllText(Application.persistentDataPath + "/MrTang2.json", jsonStr);

注意:

  • 相对JsonUtility不需要加特性
  • 不能序列化私有变量
  • 支持字曲类型
  • 需要引用LitJson命名空间
  • LitJson可以准确保存null

3.4 使用LitJson反序列化

JsonMapper.ToObject(字符串)

  1. jsonStr = File.ReadAllText(Application.persistentDataPath + "/MrTang2.json");
  2. JsonData data = JsonMapper.ToObject(jsonStr);
  3. Debug.Log(data["name"]);
  4. Debug.Log(data["age"]);
  5. MrTang2 st2 = JsonMapper.ToObject<MrTang2>(jsonStr);

注意:

  • 类结构需要无参构造函数,否则反序列化时报错
  • 字典虽然支持 但是键在使用为数值时会有问题 需要使用字符串类型

3.5 注意事项

  • Litson无需加特性
  • LitJson不支持私有变量
  • LitJson支持字典序列化反序列化
  • Litison可以直接将数据反序列化为数据集合
  • LitJson反序列化时 自定义类型需要无参构造
  • Json文档编码格式必须是UTF-8

4、Json数据管理类

另外需要LitJson代码

  1. using LitJson;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using UnityEngine;
  6. /// <summary>
  7. /// 序列化和反序列化JSON时 使用哪一种方案
  8. /// </summary>
  9. public enum JsonType
  10. {
  11. JsonUtility,
  12. LitJson
  13. }
  14. /// <summary>
  15. /// Json数据管理类 主要用于进行 json的序列化存储到硬盘 和 反序列化从硬盘中读取到内存中
  16. /// </summary>
  17. public class JsonMgr
  18. {
  19. private static JsonMgr instance = new JsonMgr();
  20. public static JsonMgr Instance
  21. {
  22. get
  23. {
  24. return instance;
  25. }
  26. }
  27. private JsonMgr() { }
  28. /// <summary>
  29. /// 存储JSON数据 序列化
  30. /// </summary>
  31. public void SavaData(object data, string fileName, JsonType jsonType = JsonType.LitJson)
  32. {
  33. //确定存储路径
  34. string path = Application.persistentDataPath + "/" + fileName + ".json";
  35. Debug.Log(path);
  36. //序列化 得到Json字符串
  37. string jsonStr = "";
  38. switch (jsonType)
  39. {
  40. case JsonType.JsonUtility:
  41. jsonStr = JsonUtility.ToJson(data);
  42. break;
  43. case JsonType.LitJson:
  44. jsonStr = JsonMapper.ToJson(data);
  45. break;
  46. default:
  47. break;
  48. }
  49. //把序列化的Json字符串 存储到指定路径中
  50. File.WriteAllText(path, jsonStr);
  51. }
  52. /// <summary>
  53. /// 读取指定文件中的 json数据 反序列化
  54. /// </summary>
  55. /// <typeparam name="T"></typeparam>
  56. /// <param name="fileName"></param>
  57. /// <param name="jsonType"></param>
  58. /// <returns></returns>
  59. public T LoadData<T>(string fileName, JsonType jsonType = JsonType.LitJson) where T : class, new()
  60. {
  61. //确定从哪个路径读取
  62. //首先先判断 默认数据文件夹中是否有我们想要的数据 如果有 就从中获取
  63. string path = Application.persistentDataPath + "/" + fileName + ".json";
  64. //先判断 是否存在这个文件
  65. //如果不存在默认文件 就从 读写文件夹中去寻找
  66. if (!File.Exists(path))
  67. path = Application.streamingAssetsPath + "/" + fileName + ".json";
  68. //如果读写文件夹中都还没有 那就返回一个默认对象
  69. if (!File.Exists(path))
  70. return new T();
  71. //进行反序列化
  72. string jsonStr = File.ReadAllText(path);
  73. T data = default(T);
  74. switch (jsonType)
  75. {
  76. case JsonType.JsonUtility:
  77. data = JsonUtility.FromJson<T>(jsonStr);
  78. break;
  79. case JsonType.LitJson:
  80. data = JsonMapper.ToObject<T>(jsonStr);
  81. break;
  82. default:
  83. break;
  84. }
  85. //把对象返回出去
  86. return data;
  87. }
  88. }

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/766655
推荐阅读
相关标签
  

闽ICP备14008679号