赞
踩
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。 易于人阅读和编写。同时也易于机器解析和生成。
JSON 数据的书写格式是:名称/值对。
名称/值对包括字段名称(在双引号中),后面写一个冒号,然后是值:
"name":"赵云"
JSON 对象在花括号中书写:
对象可以包含多个名称/值对:
{ "name":"赵云" , "level":30 }
JSON 数组在方括号中书写:
数组可包含多个对象:
- {
- "Heros": [
- { "name":"赵云" , "level":30 },
- { "name":"马超" , "level":35 },
- { "name":"关羽" , "level":15 },
- { "name":"张飞" , "level":18 },
- { "name":"黄忠" , "level":50 }
- ]
- }
1.新建一个Text文本,命名为“TestJson01.txt”。(文本内容如下)
- {
- "name":"赵云","level":30,"skill":["迅雷","狂雷天牢","连弩狂涛"]
- }
2.在Unity中创建一个“Resources/Json”文件夹,将 TestJson01.txt 文件导入在文件中。
3.新建一个类,命名为“JsonInfo.cs”,用来建立数据模型。(如下)
- [System.Serializable]
- public class JsonInfo
- {
- public string name;
- public int level;
- public string[] skill;
- }
4.新建一个类,命名为“TestJson.cs”。(代码如下)
- using UnityEngine;
-
- public class TestJson : MonoBehaviour
- {
- private void Awake()
- {
- string jsonString = Resources.Load<TextAsset>("Json/TestJson01").ToString();
- JsonInfo jsonInfo = JsonUtility.FromJson<JsonInfo>(jsonString);
-
- Debug.Log("姓名:"+jsonInfo.name);
- Debug.Log("等级:"+jsonInfo.level.ToString());
- for(int i=0;i< jsonInfo.skill.Length;i++)
- {
- Debug.Log("技能"+i+":"+ jsonInfo.skill[i]);
- }
- }
- }
5.将 TestJson.cs 挂载在场景中,并运行程序。(结果如下)
1.新建一个Text文本,命名为“TestJson01.txt”。(文本内容如下)
- {
- "Heros":[
- {"name":"赵云","level":30,"skill":["迅雷","狂雷天牢","连弩狂涛"]},
- {"name":"马超","level":35,"skill":["赤焰","赤焰燃","赤焰火海","连弩激射"]},
- {"name":"关羽","level":15,"skill":["火箭烈","火箭强袭"]},
- {"name":"张飞","level":18,"skill":["火箭天袭","龙炮","迫击龙炮"]},
- {"name":"黄忠","level":50,"skill":["贰灭元炮","肆灭元炮","太极祝融弓","八极元","龙凤天舞"," 天雷殛电"]}
- ]
- }
2.新建一个类,命名为“HeroInfo.cs”。(代码如下)
- [System.Serializable]
- public class HeroInfo
- {
- public JsonInfo[] Heros;
- }
3.新建一个类,命名为“TestJson2.cs”。(代码如下)
- using UnityEngine;
- public class TestJson2 : MonoBehaviour
- {
- private void Awake()
- {
- string jsonString = Resources.Load<TextAsset>("Json/TestJson02").ToString();
- HeroInfo heroInfos = JsonUtility.FromJson<HeroInfo>(jsonString);
-
- for (int i = 0; i < heroInfos.Heros.Length; i++)
- {
- JsonInfo jsonInfo = heroInfos.Heros[i];
-
- string nameSrt = jsonInfo.name;
- int level = jsonInfo.level;
- string skillStr = string.Empty;
- string result = string.Empty;
-
- for (int j = 0; j < jsonInfo.skill.Length; j++)
- {
- skillStr += "技能" + j + ":" + jsonInfo.skill[j];
- }
-
- result = string.Format("姓名:{0} 等级:{1} {2}", nameSrt, level, skillStr);
- print(result);
- }
- }
- }
4.将 TestJson2.cs 挂载在场景中,并运行程序。(结果如下)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。