LitJson

作者:追风剑情 发布于:2016-8-12 13:39 分类:C#

LitJson的使用

示例

using UnityEngine;
using System;
using System.IO;
using System.Collections;
using LitJson;

public class UITest : MonoBehaviour {

	void Start () {
        //创建测试对象
        A a = new A();
        a.name = "aaaaaa";
        a.age = 16;

        //写文件
        Json.WriteFile<A>(a, @"a.json");

        //读文件并解析
        A a1 = Json.ReadFile<A>(@"a.json");
        Debug.Log("name="+a1.name+", age="+a1.age);

        //读文件并解析
        JsonData data = Json.ReadFile(@"a.json");
        Debug.Log("name=" + data["name"] + ", age=" + data["age"]);
	}
}

public class A
{
    public string name;
    public int age;
}

public class Json
{
    //读*.json文件
    public static JsonData ReadFile(string path)
    {
        StreamReader sr = File.OpenText(path);
        string json = sr.ReadToEnd();
        sr.Close();
        JsonData data = JsonMapper.ToObject(json);
        return data;
    }

    public static T ReadFile<T>(string path)
    {
        StreamReader sr = File.OpenText(path);
        string json = sr.ReadToEnd();
        sr.Close();
        T data = JsonMapper.ToObject<T>(json);
        return data;
    }

    //写*.json文件
    public static void WriteFile(string json, string path)
    {
        StreamWriter sw = File.CreateText(path);
        sw.Write(json);
        sw.Flush();
        sw.Close();
    }

    public static void WriteFile<T>(T data, string path)
    {
        string json = JsonMapper.ToJson(data);
        StreamWriter sw = File.CreateText(path);
        sw.Write(json);
        sw.Flush();
        sw.Close();
    }
}

 

运行测试

11111.png

 

标签: C#

Powered by emlog  蜀ICP备18021003号   sitemap

川公网安备 51019002001593号