纳金网

标题: 数据读取与存储之json的简单存取 [打印本页]

作者: may    时间: 2019-11-24 11:07
标题: 数据读取与存储之json的简单存取

来自:Tender

一个简单的json读取与写入的工具类`
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using UnityEngine;
  5. using LitJson;

  6. public class JsonTools
  7. {
  8. /// <summary>
  9. /// 读取json 并转化为对应对象
  10. /// </summary>
  11. /// <typeparam name="T">转化为的对象类型</typeparam>
  12. /// <param name="path">json的路径</param>
  13. /// <returns>json中数据转化出的对象</returns>
  14.     public static T ReadJson<T>(string path)
  15.     {
  16.         if (string.IsNullOrEmpty(path)) {
  17.             Debug.Log("输入jsonurl为空");
  18.             return default;
  19.         }
  20.        string str= File.ReadAllText(path);
  21.         T t = JsonUtility.FromJson<T>(str);
  22.         //Litjson需要导入Litjson的dll
  23.         //  T t = JsonMapper.ToObject<T>(str);
  24.         return t;
  25.     }
  26.     /// <summary>
  27.     /// 将对象写入json
  28.     /// </summary>
  29.     /// <typeparam name="T">要写入对象的类型</typeparam>
  30.     /// <param name="t">要写入的对象</param>
  31.     /// <param name="path">要写入的json路径</param>
  32.     public static void WriteJson<T>(T t,string path)
  33.     {
  34.         if (t==null|| string.IsNullOrEmpty(path))
  35.         {
  36.             Debug.Log("请检查输入对象和路径");
  37.             return ;
  38.         }
  39.         string str = JsonUtility.ToJson(t);
  40.         //Litjson需要导入Litjson的dll
  41.         //string str = JsonMapper.ToJson(t);
  42.         File.WriteAllText(path, str);
  43.     }
  44. }
复制代码
测试脚本
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;

  5. public class Test : MonoBehaviour
  6. {
  7.     // Start is called before the first frame update
  8.     void Start()
  9.     {
  10.         
  11.     }

  12.     // Update is called once per frame
  13.     void Update()
  14.     {
  15. #if UNITY_EDITOR
  16.         if (Input.GetKeyDown(KeyCode.Q))
  17.         {
  18.             Debug.Log("q");
  19.             AA a = new AA();
  20.             a.name = "a";
  21.             a.age = 10;
  22.             JsonTools.WriteJson<AA>(a, Application.dataPath + "/Resources/aa.json");
  23.         }
  24.         if (Input.GetKeyDown(KeyCode.W))
  25.         {
  26.             Debug.Log("w");
  27.             AA a = JsonTools.ReadJson<AA>(Application.dataPath + "/Resources/aa.json");
  28.             Debug.Log("name:" + a.name);
  29.             Debug.Log("age:" + a.age);

  30.         }
  31. #endif
  32.     }
  33. }

  34. [Serializable]
  35. public class AA
  36. {
  37.     public string name = "";
  38.     public int age = 0;
  39. }
复制代码





欢迎光临 纳金网 (http://go.narkii.com/club/) Powered by Discuz! X2.5