在Unity中json文件的解析方式

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using LitJson;
using System.IO;
using System.Text;

public class JsonDate<T>
{
    
    private static JsonDate<T> instance;

    private JsonDate()
    {
         //filePath = Application.streamingAssetsPath + "/Data.json";
    }

    public static JsonDate<T> GetInstance()
    {
        if (null == instance)
        {
            instance = new JsonDate<T>();
        }
        return instance;
    }


    public List<T> GetJsonInfo(string data,string filePath)
    {
       
            
            string str = File.ReadAllText(filePath, Encoding.UTF8);
            JsonData id = JsonMapper.ToObject(str);
            JsonData levels = id[data];          
            string LevelStr = JsonMapper.ToJson(levels);
            T[] rows = JsonMapper.ToObject<T[]>(LevelStr);
            if (rows.Length > 0)
            {
            return new List<T>(rows);
            }
            return null;
           
    }
    
}

  

//解复杂json文件
public void GetJsonInfo()
{

string filename = Application.streamingAssetsPath + "/data.json";
string str = File.ReadAllText(filename);
JsonData id = JsonMapper.ToObject(str);
JsonData levels = id["TestData"];
string LevelStr = JsonMapper.ToJson(levels);
Jsonaa[] rows = JsonMapper.ToObject<Jsonaa[]>(LevelStr);
list = new List<Jsonaa>(rows);
for(int i=0;i<list.Count;++i)
{
Debug.Log(list[i].ID);
}
}

//解简单Json文件
public List<T> LoadAll()
{
string str = File.ReadAllText(filePath);
T[] rows = JsonMapper.ToObject<T[]>(str);
if(rows.Length>0)
{
return new List<T>(rows);
}
return null;
}

    public void Save(List<T> data)
    {
        string str = JsonMapper.ToJson(data);
        File.WriteAllText(filePath, str);
    }
}

  

posted @ 2019-05-24 10:51  玄~轩逸  阅读(2029)  评论(0编辑  收藏  举报