纳金网
标题:
数据读取与存储之json的简单存取
[打印本页]
作者:
may
时间:
2019-11-24 11:07
标题:
数据读取与存储之json的简单存取
来自: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;
}
复制代码
欢迎光临 纳金网 (http://go.narkii.com/club/)
Powered by Discuz! X2.5