- 最后登录
- 2019-12-25
- 注册时间
- 2012-8-24
- 阅读权限
- 90
- 积分
- 71088
- 纳金币
- 52336
- 精华
- 343
|
来自:Tender
一个简单的json读取与写入的工具类`- using System.Collections;
- using System.Collections.Generic;
- using System.IO;
- using UnityEngine;
- using LitJson;
- public class JsonTools
- {
- /// <summary>
- /// 读取json 并转化为对应对象
- /// </summary>
- /// <typeparam name="T">转化为的对象类型</typeparam>
- /// <param name="path">json的路径</param>
- /// <returns>json中数据转化出的对象</returns>
- public static T ReadJson<T>(string path)
- {
- if (string.IsNullOrEmpty(path)) {
- Debug.Log("输入jsonurl为空");
- return default;
- }
- string str= File.ReadAllText(path);
- T t = JsonUtility.FromJson<T>(str);
- //Litjson需要导入Litjson的dll
- // T t = JsonMapper.ToObject<T>(str);
- return t;
- }
- /// <summary>
- /// 将对象写入json
- /// </summary>
- /// <typeparam name="T">要写入对象的类型</typeparam>
- /// <param name="t">要写入的对象</param>
- /// <param name="path">要写入的json路径</param>
- public static void WriteJson<T>(T t,string path)
- {
- if (t==null|| string.IsNullOrEmpty(path))
- {
- Debug.Log("请检查输入对象和路径");
- return ;
- }
- string str = JsonUtility.ToJson(t);
- //Litjson需要导入Litjson的dll
- //string str = JsonMapper.ToJson(t);
- File.WriteAllText(path, str);
- }
- }
复制代码 测试脚本- using System;
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Test : MonoBehaviour
- {
- // Start is called before the first frame update
- void Start()
- {
-
- }
- // Update is called once per frame
- void Update()
- {
- #if UNITY_EDITOR
- if (Input.GetKeyDown(KeyCode.Q))
- {
- Debug.Log("q");
- AA a = new AA();
- a.name = "a";
- a.age = 10;
- JsonTools.WriteJson<AA>(a, Application.dataPath + "/Resources/aa.json");
- }
- if (Input.GetKeyDown(KeyCode.W))
- {
- Debug.Log("w");
- AA a = JsonTools.ReadJson<AA>(Application.dataPath + "/Resources/aa.json");
- Debug.Log("name:" + a.name);
- Debug.Log("age:" + a.age);
- }
- #endif
- }
- }
- [Serializable]
- public class AA
- {
- public string name = "";
- public int age = 0;
- }
复制代码 |
|