Unity3d之json解析研究
2016-10-26 15:33
218 查看
json是好东西啊!JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式
JSON简单易用,我要好好研究一下,和大家共享一下.
想了解更详细的数据可以参考一下百科:http://baike.baidu.com/view/136475.htm
好了,我们步入正题:unity3d使用json
我写了4个方法:ReadJson(),ReadJsonFromTXT();WriteJsonAndPrint(),WriteJsonToFile(string,string).
想使用JSon需要dll动态链接库
还有一些相应的命名空间using UnityEngine;
using System.Collections;
using LitJson;
using System.IO;
#if UNITY_EDITOR
using UnityEditor;
#endif
首先你需要2个字符串,一个为路径,一个文txt文件。
我的写法如下:
public TextAsset txt;
public string filePath;
public string fileName;
// Use this for initialization
void Start () {
filePath = Application.dataPath + "/TextFile";
fileName = filePath + "/File.txt";
}
1. //读json数据
void ReadJson()
{
//注意json格式。我的只能在一行写入啊,要不就报错,懂的大牛,不吝赐教啊,这是为什么呢?
string str = "{'name':'taotao','id':10,'items':[{'itemid':1001,'itemname':'dtao'},{'itemid':1002,'itemname':'test_2'}]}";
//这里是json解析了
JsonData jd = JsonMapper.ToObject(str);
Debug.Log("name=" + jd["name"]);
Debug.Log("id=" + jd["id"]);
JsonData jdItems = jd["items"];
//注意这里不能用枚举foreach,否则会报错的,看到网上
//有的朋友用枚举,但是我测试过,会报错,我也不太清楚。
//大家注意一下就好了
for (int i = 0; i < jdItems.Count; i++)
{
Debug.Log("itemid=" + jdItems["itemid"]);
Debug.Log("itemname=" + jdItems["itemname"]);
}
Debug.Log("items is or not array,it's " + jdItems.IsArray);
}
2. //从TXT文本里都json
void ReadJsonFromTXT()
{
//解析json
JsonData jd = JsonMapper.ToObject(txt.text);
Debug.Log("hp:" + jd["hp"]);
Debug.Log("mp:" + jd["mp"]);
JsonData weapon = jd["weapon"];
//打印一下数组
for (int i = 0; i < weapon.Count; i++)
{
Debug.Log("name="+weapon["name"]);
Debug.Log("color="+weapon["color"]);
Debug.Log("durability="+weapon["durability"]);
}
}
3. //写json数据并且打印他
void WriteJsonAndPrint()
{
System.Text.StringBuilder strB = new System.Text.StringBuilder();
JsonWriter jsWrite = new JsonWriter(strB);
jsWrite.WriteObjectStart();
jsWrite.WritePropertyName("Name");
jsWrite.Write("taotao");
jsWrite.WritePropertyName("Age");
jsWrite.Write(25);
jsWrite.WritePropertyName("MM");
jsWrite.WriteArrayStart();
jsWrite.WriteObjectStart();
jsWrite.WritePropertyName("name");
jsWrite.Write("xiaomei");
jsWrite.WritePropertyName("age");
jsWrite.Write("17");
jsWrite.WriteObjectEnd();
jsWrite.WriteObjectStart();
jsWrite.WritePropertyName("name");
jsWrite.Write("xiaoli");
jsWrite.WritePropertyName("age");
jsWrite.Write("18");
jsWrite.WriteObjectEnd();
jsWrite.WriteArrayEnd();
jsWrite.WriteObjectEnd();
Debug.Log(strB);
JsonData jd = JsonMapper.ToObject(strB.ToString());
Debug.Log("name=" + jd["Name"]);
Debug.Log("age=" + jd["Age"]);
JsonData jdItems = jd["MM"];
for (int i = 0; i < jdItems.Count; i++)
{
Debug.Log("MM name=" + jdItems["name"]);
Debug.Log("MM age=" + jdItems["age"]);
}
}
4. //把json数据写到文件里
void WriteJsonToFile(string path,string fileName)
{
System.Text.StringBuilder strB = new System.Text.StringBuilder();
JsonWriter jsWrite = new JsonWriter(strB);
jsWrite.WriteObjectStart();
jsWrite.WritePropertyName("Name");
jsWrite.Write("taotao");
jsWrite.WritePropertyName("Age");
jsWrite.Write(25);
jsWrite.WritePropertyName("MM");
jsWrite.WriteArrayStart();
jsWrite.WriteObjectStart();
jsWrite.WritePropertyName("name");
jsWrite.Write("xiaomei");
jsWrite.WritePropertyName("age");
jsWrite.Write("17");
jsWrite.WriteObjectEnd();
jsWrite.WriteObjectStart();
jsWrite.WritePropertyName("name");
jsWrite.Write("xiaoli");
jsWrite.WritePropertyName("age");
jsWrite.Write("18");
jsWrite.WriteObjectEnd();
jsWrite.WriteArrayEnd();
jsWrite.WriteObjectEnd();
Debug.Log(strB);
//创建文件目录
DirectoryInfo dir = new DirectoryInfo(path);
if (dir.Exists)
{
Debug.Log("This file is already exists");
}
else
{
Directory.CreateDirectory(path);
Debug.Log("CreateFile");
#if UNITY_EDITOR
AssetDatabase.Refresh();
#endif
}
//把json数据写到txt里
StreamWriter sw;
if (File.Exists(fileName))
{
//如果文件存在,那么就向文件继续附加(为了下次写内容不会覆盖上次的内容)
sw = File.AppendText(fileName);
Debug.Log("appendText");
}
else
{
//如果文件不存在则创建文件
sw = File.CreateText(fileName);
Debug.Log("createText");
}
sw.WriteLine(strB);
sw.Close();
#if UNITY_EDITOR
AssetDatabase.Refresh();
#endif
}.
为了大家可以更形象理解一下。我用GUI了
void OnGUI()
{
GUILayout.BeginArea(new Rect(0, 0, Screen.width, Screen.height));
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.BeginVertical();
GUILayout.FlexibleSpace();
if (GUILayout.Button("ReadJson"))
{
ReadJson();
}
if (GUILayout.Button("ReadJsonFromTXT"))
{
ReadJsonFromTXT();
}
if (GUILayout.Button("WriteJsonAndPrint"))
{
WriteJsonAndPrint();
}
if (GUILayout.Button("WriteJsonToFile"))
{
WriteJsonToFile(filePath,fileName);
}
GUILayout.FlexibleSpace();
GUILayout.EndVertical();
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.EndArea();
}
首先我的工程如下:
![](http://image58.360doc.com/DownloadImg/2013/01/1711/29659593_1)
接着我们把TestJson脚本赋给摄像机
![](http://image58.360doc.com/DownloadImg/2013/01/1711/29659593_2)
我们点击run一下
![](http://image58.360doc.com/DownloadImg/2013/01/1711/29659593_3)
你便会在游戏面板里看到有4个按钮了
![](http://image58.360doc.com/DownloadImg/2013/01/1711/29659593_4)
我们点击ReadJson按钮一下
![](http://image58.360doc.com/DownloadImg/2013/01/1711/29659593_5)
在相印的控制台里打印如红色框内
![](http://image58.360doc.com/DownloadImg/2013/01/1711/29659593_6)
我们clear一下控制台,clear玩了如下所示,红色区域里什么也没有了
![](http://image58.360doc.com/DownloadImg/2013/01/1711/29659593_7)
我们点击一下ReadJsonFromTXT按钮,点完后发现打印的结果和txt里的内容一模一样,呵呵成功了
![](http://image58.360doc.com/DownloadImg/2013/01/1711/29659593_8)
我们再clear一下控制台,之后点击一下WriteJsonAndPrint按钮
![](http://image58.360doc.com/DownloadImg/2013/01/1711/29659593_9)
打印结果如下:
![](http://image58.360doc.com/DownloadImg/2013/01/1711/29659593_10)
我们接着clear一下控制台,点击一下WriteJsonToFile按钮
![](http://image58.360doc.com/DownloadImg/2013/01/1711/29659593_11)
我们发现在工程面板里多出来了一个文件夹和文本文件,而且控制台打印的结果和文本里的内容一样哟!o(∩_∩)o
![](http://image58.360doc.com/DownloadImg/2013/01/1711/29659593_12)
好了,这节讲完了。不知道大家清楚没,欢迎留言。一起学习,一起进步。
请保证工程里面已经加入了LitJson.dll
服务器上JSON的内容
[{"people":[
{"name":"fff","pass":"123456","age":"1", "info":{"sex":"man"}},
{"name":"god","pass":"123456","age":"1","info":{"sex":"woman"}},
{"name":"kwok","pass":"123456","age":"1","info":{"sex":"man"}},
{"name":"tom","pass":"123456","age":"1","info":{"sex":"woman"}}
]}
]
复制代码
LoadControl_c代码:
using UnityEngine;
using System.Collections;
using LitJson;
public class LoadControl_c:MonoBehaviour
{
private GameObject plane;
public string url = "http://127.0.0.1/test2.txt";
// Use this for initialization
void Start()
{
StartCoroutine(LoadTextFromUrl());
//StartCoroutine(DoSomething());
//Book book = new Book("Android dep");
//InvokeRepeating("LaunchProjectile", 1, 5);
}
IEnumerator DoSomething()
{
yield return new WaitForSeconds(3);
}
IEnumerator LoadTextFromUrl()
{
if (url.Length > 0)
{
WWW www = new WWW(url);
yield return www;
//string data = www.data.ToString().Substring(1);
string data = www.text.ToString().Substring(1);
// 下面是关键
print(data);
LitJson.JsonData jarr = LitJson.JsonMapper.ToObject(www.text);
if(jarr.IsArray)
{
for (int i = 0; i < jarr.Count; i++)
{
Debug.Log(jarr[i]["people"]);
JsonData jd = jarr[i]["people"];
for(int j = 0; j < jd.Count; j++)
{
Debug.Log(jd[j]["name"]);
}
}
}
}
}
}
原文链接:http://www.360doc.com/content/13/0117/11/10941785_260687703.shtml#
JSON简单易用,我要好好研究一下,和大家共享一下.
想了解更详细的数据可以参考一下百科:http://baike.baidu.com/view/136475.htm
好了,我们步入正题:unity3d使用json
我写了4个方法:ReadJson(),ReadJsonFromTXT();WriteJsonAndPrint(),WriteJsonToFile(string,string).
想使用JSon需要dll动态链接库
还有一些相应的命名空间using UnityEngine;
using System.Collections;
using LitJson;
using System.IO;
#if UNITY_EDITOR
using UnityEditor;
#endif
首先你需要2个字符串,一个为路径,一个文txt文件。
我的写法如下:
public TextAsset txt;
public string filePath;
public string fileName;
// Use this for initialization
void Start () {
filePath = Application.dataPath + "/TextFile";
fileName = filePath + "/File.txt";
}
1. //读json数据
void ReadJson()
{
//注意json格式。我的只能在一行写入啊,要不就报错,懂的大牛,不吝赐教啊,这是为什么呢?
string str = "{'name':'taotao','id':10,'items':[{'itemid':1001,'itemname':'dtao'},{'itemid':1002,'itemname':'test_2'}]}";
//这里是json解析了
JsonData jd = JsonMapper.ToObject(str);
Debug.Log("name=" + jd["name"]);
Debug.Log("id=" + jd["id"]);
JsonData jdItems = jd["items"];
//注意这里不能用枚举foreach,否则会报错的,看到网上
//有的朋友用枚举,但是我测试过,会报错,我也不太清楚。
//大家注意一下就好了
for (int i = 0; i < jdItems.Count; i++)
{
Debug.Log("itemid=" + jdItems["itemid"]);
Debug.Log("itemname=" + jdItems["itemname"]);
}
Debug.Log("items is or not array,it's " + jdItems.IsArray);
}
2. //从TXT文本里都json
void ReadJsonFromTXT()
{
//解析json
JsonData jd = JsonMapper.ToObject(txt.text);
Debug.Log("hp:" + jd["hp"]);
Debug.Log("mp:" + jd["mp"]);
JsonData weapon = jd["weapon"];
//打印一下数组
for (int i = 0; i < weapon.Count; i++)
{
Debug.Log("name="+weapon["name"]);
Debug.Log("color="+weapon["color"]);
Debug.Log("durability="+weapon["durability"]);
}
}
3. //写json数据并且打印他
void WriteJsonAndPrint()
{
System.Text.StringBuilder strB = new System.Text.StringBuilder();
JsonWriter jsWrite = new JsonWriter(strB);
jsWrite.WriteObjectStart();
jsWrite.WritePropertyName("Name");
jsWrite.Write("taotao");
jsWrite.WritePropertyName("Age");
jsWrite.Write(25);
jsWrite.WritePropertyName("MM");
jsWrite.WriteArrayStart();
jsWrite.WriteObjectStart();
jsWrite.WritePropertyName("name");
jsWrite.Write("xiaomei");
jsWrite.WritePropertyName("age");
jsWrite.Write("17");
jsWrite.WriteObjectEnd();
jsWrite.WriteObjectStart();
jsWrite.WritePropertyName("name");
jsWrite.Write("xiaoli");
jsWrite.WritePropertyName("age");
jsWrite.Write("18");
jsWrite.WriteObjectEnd();
jsWrite.WriteArrayEnd();
jsWrite.WriteObjectEnd();
Debug.Log(strB);
JsonData jd = JsonMapper.ToObject(strB.ToString());
Debug.Log("name=" + jd["Name"]);
Debug.Log("age=" + jd["Age"]);
JsonData jdItems = jd["MM"];
for (int i = 0; i < jdItems.Count; i++)
{
Debug.Log("MM name=" + jdItems["name"]);
Debug.Log("MM age=" + jdItems["age"]);
}
}
4. //把json数据写到文件里
void WriteJsonToFile(string path,string fileName)
{
System.Text.StringBuilder strB = new System.Text.StringBuilder();
JsonWriter jsWrite = new JsonWriter(strB);
jsWrite.WriteObjectStart();
jsWrite.WritePropertyName("Name");
jsWrite.Write("taotao");
jsWrite.WritePropertyName("Age");
jsWrite.Write(25);
jsWrite.WritePropertyName("MM");
jsWrite.WriteArrayStart();
jsWrite.WriteObjectStart();
jsWrite.WritePropertyName("name");
jsWrite.Write("xiaomei");
jsWrite.WritePropertyName("age");
jsWrite.Write("17");
jsWrite.WriteObjectEnd();
jsWrite.WriteObjectStart();
jsWrite.WritePropertyName("name");
jsWrite.Write("xiaoli");
jsWrite.WritePropertyName("age");
jsWrite.Write("18");
jsWrite.WriteObjectEnd();
jsWrite.WriteArrayEnd();
jsWrite.WriteObjectEnd();
Debug.Log(strB);
//创建文件目录
DirectoryInfo dir = new DirectoryInfo(path);
if (dir.Exists)
{
Debug.Log("This file is already exists");
}
else
{
Directory.CreateDirectory(path);
Debug.Log("CreateFile");
#if UNITY_EDITOR
AssetDatabase.Refresh();
#endif
}
//把json数据写到txt里
StreamWriter sw;
if (File.Exists(fileName))
{
//如果文件存在,那么就向文件继续附加(为了下次写内容不会覆盖上次的内容)
sw = File.AppendText(fileName);
Debug.Log("appendText");
}
else
{
//如果文件不存在则创建文件
sw = File.CreateText(fileName);
Debug.Log("createText");
}
sw.WriteLine(strB);
sw.Close();
#if UNITY_EDITOR
AssetDatabase.Refresh();
#endif
}.
为了大家可以更形象理解一下。我用GUI了
void OnGUI()
{
GUILayout.BeginArea(new Rect(0, 0, Screen.width, Screen.height));
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.BeginVertical();
GUILayout.FlexibleSpace();
if (GUILayout.Button("ReadJson"))
{
ReadJson();
}
if (GUILayout.Button("ReadJsonFromTXT"))
{
ReadJsonFromTXT();
}
if (GUILayout.Button("WriteJsonAndPrint"))
{
WriteJsonAndPrint();
}
if (GUILayout.Button("WriteJsonToFile"))
{
WriteJsonToFile(filePath,fileName);
}
GUILayout.FlexibleSpace();
GUILayout.EndVertical();
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.EndArea();
}
首先我的工程如下:
接着我们把TestJson脚本赋给摄像机
我们点击run一下
你便会在游戏面板里看到有4个按钮了
我们点击ReadJson按钮一下
在相印的控制台里打印如红色框内
我们clear一下控制台,clear玩了如下所示,红色区域里什么也没有了
我们点击一下ReadJsonFromTXT按钮,点完后发现打印的结果和txt里的内容一模一样,呵呵成功了
我们再clear一下控制台,之后点击一下WriteJsonAndPrint按钮
打印结果如下:
我们接着clear一下控制台,点击一下WriteJsonToFile按钮
我们发现在工程面板里多出来了一个文件夹和文本文件,而且控制台打印的结果和文本里的内容一样哟!o(∩_∩)o
好了,这节讲完了。不知道大家清楚没,欢迎留言。一起学习,一起进步。
请保证工程里面已经加入了LitJson.dll
服务器上JSON的内容
[{"people":[
{"name":"fff","pass":"123456","age":"1", "info":{"sex":"man"}},
{"name":"god","pass":"123456","age":"1","info":{"sex":"woman"}},
{"name":"kwok","pass":"123456","age":"1","info":{"sex":"man"}},
{"name":"tom","pass":"123456","age":"1","info":{"sex":"woman"}}
]}
]
复制代码
LoadControl_c代码:
using UnityEngine;
using System.Collections;
using LitJson;
public class LoadControl_c:MonoBehaviour
{
private GameObject plane;
public string url = "http://127.0.0.1/test2.txt";
// Use this for initialization
void Start()
{
StartCoroutine(LoadTextFromUrl());
//StartCoroutine(DoSomething());
//Book book = new Book("Android dep");
//InvokeRepeating("LaunchProjectile", 1, 5);
}
IEnumerator DoSomething()
{
yield return new WaitForSeconds(3);
}
IEnumerator LoadTextFromUrl()
{
if (url.Length > 0)
{
WWW www = new WWW(url);
yield return www;
//string data = www.data.ToString().Substring(1);
string data = www.text.ToString().Substring(1);
// 下面是关键
print(data);
LitJson.JsonData jarr = LitJson.JsonMapper.ToObject(www.text);
if(jarr.IsArray)
{
for (int i = 0; i < jarr.Count; i++)
{
Debug.Log(jarr[i]["people"]);
JsonData jd = jarr[i]["people"];
for(int j = 0; j < jd.Count; j++)
{
Debug.Log(jd[j]["name"]);
}
}
}
}
}
}
原文链接:http://www.360doc.com/content/13/0117/11/10941785_260687703.shtml#
相关文章推荐
- Unity3D研究院之将场景导出XML或JSON或二进制并且解析还原场景(四十二)(转自雨松MOMO)
- Unity3D中使用MiniJson解析json的例子
- (转)Unity3D研究院之将场景导出XML或JSON或二进制并且解析还原场景
- Unity3D 场景导出成 XML或JSON 并解析还原场景
- Unity3D研究院之使用 C#合成解析XML与JSON
- unity3d请求json数据并解析
- Unity3d Json解析库
- Unity3D使用 C#实现合成解析XML与JSON(四十一)
- Unity3D 游戏引擎之将场景导出XML或JSON或二进制并且解析还原场景
- Unity3D研究之MAC&Windows跨平台解析Excel
- unity3d 使用LitJson解析 JSON格式数据
- unity3d场景导出XML或JSON并且解析还原场景
- Unity3D 游戏引擎之使用 C#合成解析XML与JSON
- unity3d中使用DLL库和解析json
- Unity3d-XML文件数据解析&JSON数据解析
- Unity3D中使用MiniJson解析json的例子
- Unity3D 游戏引擎之将场景导出XML或JSON或二进制并且解析还原场景
- [Unity3d]u3d请求json数据并解析
- Unity3D中使用MiniJson解析json的例子
- (转载)Unity3D研究院之使用 C#合成解析XML与JSON(四十一)