Unity 入门教程 之 快速学会读取Json数据
1、JsonUtility:
Utility functions for working with JSON data.
2、
JsonUtility.FromJson:
Create an object from its JSON representation.
Internally, this method uses the Unity serializer; therefore the type you are creating must be supported by the serializer. It must be a plain class/struct marked with the Serializable attribute. Fields of the object must have types supported by the serializer. Fields that have unsupported types, as well as private fields or fields marked with the NonSerialized attribute, will be ignored.
3、注意事项提醒:
在使用JsonUtility.ToJson(),数据记得“Serializable”,例如:
[Serializable]
public class PersonInfo {
public string name;
public int age;
}
1、打开Unity,新建一个空工程,然后Unity界面如下图
2、在工程中新建一个脚本,脚本可以命名为“JsonUtilityTest”,选中脚本,双击脚本或者右键“Open C# Project”,具体如下图
3、在打开的“JsonUtilityTest”脚本上进行代码编辑,首先定义两个数据类,用来便于储存数据信息,并把“Serializable”数据类,具体代码及代码说明如下图
4、在打开的“JsonUtilityTest”脚本上进行代码编辑,然后通过上面定义好的数据类用来设置信息,并且通过JsonUtility.ToJson()把数据Json化,接着再通过JsonUtility.FromJson()来读取解析Json数据,并且把数据打印出来,具体代码及代码说明如下图
5、具体脚本内容如下:
using System;
using UnityEngine;
[Serializable]
public class PersonInfo {
public string name;
public int age;
}
[Serializable]
public class Person {
public PersonInfo[] persons;
}
public class JsonUtilityTest : MonoBehaviour {
// Use this for initialization
void Start () {
PersonInfo person1 = new PersonInfo();
person1.name = "Amy";
person1.age = 27;
PersonInfo person2 = new PersonInfo();
person2.name = "Benny";
person2.age = 18;
PersonInfo[] persons = new PersonInfo[] {person1, person2 };
Person person = new Person();
person.persons = persons;
string personsInfo = JsonUtility.ToJson(person);
print("人员信息:\r\n " +personsInfo);
Person GetPersonInfo = JsonUtility.FromJson<Person>(personsInfo);
foreach (var personInfo in GetPersonInfo.persons) {
print(personInfo.name + " " + personInfo.age);
}
}
}
6、脚本编译正确后,回到Unity界面,在场景中新建一个“GameObject”,然后把脚本“JsonUtilityTest ”赋给“GameObject”,具体如下图
7、运行场景,即可看到数据以Json格式打印在控制台Console上,具体如下图
8、到此,《Unity 入门教程 之 快速学会读取Json数据》讲解结束,谢谢