Unity 入门教程 之 快速学会读取Json数据

2024-10-22 15:06:02

Unity 入门教程 之 快速学会读取Json数据。Json数据格式化,如何读取Json格式的数据,本节通过Unity自带的Json来读取解析Json数据,具体如下

工具/原料

Unity

JsonUtility

一、基本概念

1、JsonUtility:Utility functions for working with JSON data.

2、JsonUtility.FromJson:Create an object from its JSON representation.Internally, th足毂忍珩is 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;}

二、入门教程 之 快速学会读取Json数据

1、打开Unity,新建一个空工程,然后Unity界面如下图

Unity 入门教程 之 快速学会读取Json数据

3、在打开的“JsonUtilityTest”脚本上进行代码编辑,首先定义两个数据类,用来便于储存数据信息,并把“Serializable”数据类,具体代码及代码说明如下图

Unity 入门教程 之 快速学会读取Json数据

5、具体脚本内容如下:using System;us坡纠课柩ing UnityEngine;[Serializable]publ足毂忍珩ic 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”,具体如下图

Unity 入门教程 之 快速学会读取Json数据

8、到此,《Unity 入门教程 之 快速学会读取Json数据》讲解结束,谢谢

猜你喜欢