Unity——JSON的读取

4 篇文章 0 订阅

一、读取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.ToObject<StudentsData>(jsonString);

        List<Student> 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 List<Student> 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 命名空间。

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Unity中,你可以使用JsonUtility类来读取和解析JSON数据。下面是一个简单的示例代码,演示如何使用JsonUtility来读取JSON数据并将其转化为对象: ```csharp using UnityEngine; using System.IO; public class JSONReader : MonoBehaviour { void Start() { // 读取JSON文件 string jsonFilePath = Application.streamingAssetsPath + "/data.json"; string jsonData = File.ReadAllText(jsonFilePath); // 将JSON数据转化为对象 MyDataObject dataObject = JsonUtility.FromJson<MyDataObject>(jsonData); // 在控制台输出对象的属性 Debug.Log("Name: " + dataObject.name); Debug.Log("Age: " + dataObject.age); Debug.Log("Score: " + dataObject.score); } } [System.Serializable] public class MyDataObject { public string name; public int age; public float score; } ``` 在上面的示例中,我们首先使用`File.ReadAllText`方法从JSON文件中读取数据。然后,使用`JsonUtility.FromJson`方法将JSON数据转化为`MyDataObject`对象。最后,我们可以通过访问对象的属性来获取JSON数据中的值。 请注意,为了使对象与JSON数据匹配,我们使用了`[System.Serializable]`特性来标记`MyDataObject`类。 确保将上述脚本附加到场景中的某个游戏对象上,并创建一个名为"data.json"的JSON文件,并将其放置在Unity的StreamingAssets文件夹下。这样,当你运行游戏时,脚本将读取JSON文件并输出数据。 希望能对你有所帮助!如果你有任何其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

七七喝椰奶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值