把对象转换为字节序列的过程称为对象的序列化。

把字节序列化恢复为对象过程称为对象的反序列化。


JSON格式的转换,是一大神给我说的,让我拿来存储数据库时对一些数据的处理,感觉特别好用。但是我并没有深入的去学习,这里只是最简单的应用,以下就是一个简单的示例程序。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;  //需要下载Newtonsoft.Json.dll文件,放在Plugins文件夹下
using System.IO;

public class json : MonoBehaviour {

	// Use this for initialization
	void Start () {
        writeTxt();//调用写入文本函数
        StartCoroutine(testJson());//调用读取函数
	}
	
    void writeTxt()
    {
        MapPosList maplist = new MapPosList();
        maplist.points = new List<GetPointXY>();
        maplist.points.Add(new GetPointXY(100, 78));
        maplist.points.Add(new GetPointXY(54, 121));
        maplist.points.Add(new GetPointXY(56, 845));
        maplist.points.Add(new GetPointXY(221, 56));
        maplist.points.Add(new GetPointXY(454, 23));
        maplist.points.Add(new GetPointXY(10, 12));
        maplist.points.Add(new GetPointXY(45, 65));
        maplist.points.Add(new GetPointXY(898, 887));
        //用json将一个对象转成一个字符串
        string str = JsonConvert.SerializeObject(maplist);

        //下面将这个字符串写入本地文本
        StreamWriter sw;
        FileInfo t = new FileInfo("Assets/Streaming Assets/test.txt");
        if (!t.Exists)
        {
            sw = t.CreateText();
        }
        else
        {
            sw = t.AppendText();
        }
        sw.Write(str);
        sw.Close();
        sw.Dispose();
    }
    IEnumerator testJson()
    {
        WWW w = new WWW("file:///D:/Test/Assets/Streaming Assets/test.txt");
        yield return w;

        string str = w.text.Trim();
        //通过json将字符串转换成一个对象
        MapPosList data = JsonConvert.DeserializeObject<MapPosList>(str);
        Debug.Log(data.points[0].xPosition);
        yield return null;
    }
    
}
public class GetPointXY
{
    public float xPosition;
    public float yposition;
    public GetPointXY(float x, float y)
    {
        this.xPosition = x;
        this.yposition = y;
    }
}
public class MapPosList
{
    public List<GetPointXY> points;
}


这里最重要的就是JSON的两个函数:

JsonConvert.SerializeObject//将对象转换为字符串

JsonConvert.DeserializeObject//将字符串恢复为一个对象


这里备份一个Newtonsoft.Json.dll的下载链接,好像各版本都有:

http://yunpan.cn/cK5Ih7aMmy4ZH  访问密码 b6a4



GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 天前 )
960b763e 2 个月前
8c391e04 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐