unity json mysql_Unity 数据Json格式的转换

本文介绍如何在Unity中使用Newtonsoft.Json库进行JSON格式的数据转换。通过示例展示了如何将对象序列化为字符串并保存到文本文件,以及如何从文本文件反序列化回对象。主要涉及JsonConvert.SerializeObject和JsonConvert.DeserializeObject两个关键函数。
摘要由CSDN通过智能技术生成

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

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

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();

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(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 points;

}

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

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值