深圳做网站报价,闵行北京网站建设,上海手机网站制作公司,天津哪家制作网站好一、读取JSON
在实际中#xff0c;读取JSON比保存JSON重要得多。因为存档、发送数据包往往可以采用其他序列化方法#xff0c;但游戏的配置文件使用JSON格式比较常见。游戏的配置数据不属于动态数据#xff0c;属于游戏资源#xff0c;但很适合用JSON表示。
下面以一个简…一、读取JSON
在实际中读取JSON比保存JSON重要得多。因为存档、发送数据包往往可以采用其他序列化方法但游戏的配置文件使用JSON格式比较常见。游戏的配置数据不属于动态数据属于游戏资源但很适合用JSON表示。
下面以一个简单的JSON数据文件为例演示读取JSON。从整体上看有两种思路 直接整体反序列化为数据对象通过写代码逐步读取内容 {students: [{name: Alice,age: 20,major: Computer Science},{name: Bob,age: 22,major: Engineering},{name: Carol,age: 21,major: Business}]
}
1、整体反序列化
LitJSON库支持直接将JSON字符串反序列化为C#对象但是为了方便使用最好先准备一个数据结构与JSON完全对应的对象。示例如下
[System.Serializable]
public class Student
{public string name;public int age;public string major;
}
这个类使用了[System.Serializable]属性以便在序列化和反序列化 JSON 数据时能够正确处理。该类有三个属性分别表示学生的姓名name、年龄age和专业major。 用LitJson.JsonMapper方法实现反序列化
using UnityEngine;
using System.Collections.Generic;
using LitJson;public class JSONDeserializer : MonoBehaviour
{public TextAsset jsonFile;void Start(){string jsonString jsonFile.text;StudentsData data JsonMapper.ToObjectStudentsData(jsonString);ListStudent students data.students;// 遍历学生列表并输出信息foreach (Student student in students){Debug.Log(Name: student.name);Debug.Log(Age: student.age);Debug.Log(Major: student.major);Debug.Log(------------------);}}
}[System.Serializable]
public class StudentsData
{public ListStudent students;
}[System.Serializable]
public class Student
{public string name;public int age;public string major;
}
JSON源文件应当放在Resources/Json文件夹下将上文的脚本挂载到任意物体上即可进行测试系统会在Console窗口中输出所有道具的信息。
可以看到直接序列化对象的优点是简单易行只要定义好了数据类型就可以直接将JSON转化为方便实用的对象。但缺点也很明显即JSON对数据类型的要求十分严格。
2、分步获取数据
下面是分布读取JSON信息的例子
using UnityEngine;
using System.Collections.Generic;
using LitJson;public class JSONDeserializer : MonoBehaviour
{public TextAsset jsonFile;void Start(){string jsonString jsonFile.text;JsonData jsonData JsonMapper.ToObject(jsonString);// 读取顶层数据对象string name (string)jsonData[name];int age (int)jsonData[age];string major (string)jsonData[major];Debug.Log(Name: name);Debug.Log(Age: age);Debug.Log(Major: major);Debug.Log(------------------);// 读取嵌套对象列表JsonData studentsData jsonData[students];for (int i 0; i studentsData.Count; i){JsonData studentData studentsData[i];string studentName (string)studentData[name];int studentAge (int)studentData[age];string studentMajor (string)studentData[major];Debug.Log(Name: studentName);Debug.Log(Age: studentAge);Debug.Log(Major: studentMajor);Debug.Log(------------------);}}
}
这个示例代码假设 JSON 数据文件的顶层结构与上述示例相同。在Start方法中我们首先将 JSON 字符串解析为JsonData对象然后逐行读取其中的数据。
首先我们读取顶层数据对象的姓名、年龄和专业并打印到日志中。然后我们读取名为students的嵌套对象列表使用循环迭代每个学生的数据。在每次迭代中我们读取学生对象的姓名、年龄和专业并打印到日志中。
通过这种方式你可以逐行读取 JSON 数据并按需处理其中的内容。注意要将 JSON 数据文件分配给jsonFile变量并确保引入了 LitJson 命名空间。