常用Txt、Json等文件数据转换方法

1、LitJson插件(读档)

T datas = LitJson.JsonMapper.ToObject<T>(string value);

List<T> cityIds = LitJson.JsonMapper.ToObject<List<T>>(string s);

(1)读取 Resources文件夹下的WeatherId.txt文件;

public static bool initDic = false;
    public static Dictionary<string,int> posToId = new Dictionary<string,int>();

    public static List<CityId> cityIds = new List<CityId>();

    public static int GetWeatherId(string cityName)
    {
        int id = 0;
        if (!initDic)
        {
            initDic = true;
            TextAsset ta = Resources.Load<TextAsset>("WeatherId");
            cityIds = LitJson.JsonMapper.ToObject<List<CityId>>(ta.text);
        }
        return id;
    }

(2)读取 FilePath路径下的Json文件;

using System;
using UnityEngine;
using System.IO;

    public T ReadDatasJson<T>(string FilePath)
    {
        StreamReader sr = new StreamReader(FilePath);
        string ReadStr = sr.ReadToEnd();
        sr.Close();
        try
        {
            T fileDatas = LitJson.JsonMapper.ToObject<T>(ReadStr);
            return fileDatas;
        }
        catch (Exception)
        {
            Debug.LogError("本地设置文档格式错误,设置已重置");
            File.Delete(FilePath);
            return null;
        }
    }

2、Newtonsoft.Json(存档)

string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(object value, Newtonsoft.Json.Formatting.Indented);

将T类型里的数据转为string字符,并存到filePath路径下的json文件里,json格式保存;

using System.IO;

private void SaveDatasJson<T>(T value)
    {
        string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.Indented);
        StreamWriter sw = new StreamWriter(filePath);
        sw.WriteLine(jsonStr);
        sw.Close();
    }

3、JsonUtility(将从本地文件/服务器等获取到的字符,转化为目标格式)

List<T1> newMessages = JsonUtility.FromJson<T2>(string value).data;

List<T1> newMessages = JsonUtility.FromJson<List<T1>>(string value);

数据类型格式:T1,T2;

[Serializable]
public class T1
{
    public string Mes;
    public string Type;
}

[Serializable]
public class T2
{
    public bool success;//true
    public string message;//null
    public List<T1> data;
    /*[
     * {"Mes":"2021-01-19","Type":0}
     * {"Mes":"2028-03-29","Type":1}
     * {"Mes":"2011-11-22","Type":2}
     * ]
     */
}

将从服务器里获得的string字符信息,转化提取为指定格式的数据; 

    /// <summary>
    /// 隔一分钟获取一次数据
    /// </summary>
    /// <param name="tokenSource"></param>
    /// <returns></returns>
    public async Task GetWarnMessagesTask()
    {
        string _url = string.Concat(host, url);

        while (true)
        {
            //获取到数据后,把数据格式转化为目标格式
            string getData = HttpGet(_url);
            List<T1> newMessages = JsonUtility.FromJson<T2>(getData).data;

            ...
            ...
            ...

            //等60秒后重新获取数据
            await Task.Delay(TimeSpan.FromSeconds(60f));
        }
    }

注:LitJson、JsonUtility相对Newtonsoft.Json来说,对数据参数格式要求更严格;

有可能出现缺少属性,找不到属性等报错;

比如;服务端有4个参数,脚本只写了三个所需的参数这种属性非一一对应情况

Newtonsoft.Json兼容性相对更强些,格式转换,属性参数不一一对应时,会选择性跳过等;

注:如有理解认识错误处,欢迎指出。 

猜你喜欢

转载自blog.csdn.net/weixin_43908355/article/details/125293013