Unity3D_使用JsonUtility读取Json

使用Unity内置的方法对json进行写入与读取,不依赖任何插件和dll

使用到的API

  读取:

    JsonUtility.FromJson<T>(string json)

    JsonUtility.FromJsonOverwrite(string json, object objectToOverwrite)

  写入:

    JsonUtility.ToJson(object  obj)

____________________________________________________

以“答题”作为示例讲解 json 的读取与写入

一、首先我们需要创建一个“答题” 的类,该类包括:题目、选项(A、B、C、D)、答案

// 一个完整的“问题”类(注意:一定要序列化,不序列化读不出来,序列化的意思就是:在创建类的上一行加上[Serializable])
[Serializable]
public class AloneQuestion
{
    public string title;
    public string A;
    public string B;
    public string C;
    public string D;
    public string answer;
}

二、上面的类只代表一道题,实际应用中我们可能有很多题,所以我们需要创建一个“题库”类

// “题库”类的变量,就是“问题”类的数组(注意:一定要序列化,不序列化读不出来)
[Serializable]
public class AllQuestion
{
    public AloneQuestion[] questions;

三、类创建完了,那么怎么写与类对应的 json 呢

 

 

建议使用 Visual Studio 编辑写json文件,

在使用 Visual Studio 编辑 json 文件的时候编辑器指出json文件编辑时的错误,

省去了去网站校验 json 的步骤,但是仍在此提供一个校验 json 的网站 JSON在线校验格式化工具(Be JSON)

注意:json中不能用双斜杠(//)注释,否则在读取的时候会报错

____________________________________________________

完整代码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class WiWi_JsonUsage : MonoBehaviour
{
    // Update is called once per frame
    void Update()
    {
        // 按 W 写入json,按 R 读取json并打印到控制台
        if (Input.GetKeyDown(KeyCode.W))
        {
            WriteJson();
        }
        else if (Input.GetKeyDown(KeyCode.R))
        {
            ReadJson01();
        }
        else if (Input.GetKeyDown(KeyCode.Space))
        {
            ReadJson02();
        }
    }
    // 读取 json (方法一)
    private void ReadJson01()
    {
        AllQuestion allq = new AllQuestion();
        // Json 文件的路径
        string path = File.ReadAllText(Application.streamingAssetsPath + "/Question.json");
        // 文件内容存到本地
        allq = JsonUtility.FromJson<AllQuestion>(path);

        // 将读取的内容打印到控制台
        string str = "Json 文件读取成功,内容如下:\n\n";
        for (int i = 0; i < allq.questions.Length; i++)
        {
            str += "问题:" + allq.questions[i].title + "\n";
            str += "A、" + allq.questions[i].A + "\n";
            str += "B、" + allq.questions[i].B + "\n";
            str += "C、" + allq.questions[i].C + "\n";
            str += "D、" + allq.questions[i].D + "\n";
            str += "答案:" + allq.questions[i].answer + "\n\n";
        }
        print(str);
    }
    // 读取 json (方法二)
    public AloneQuestion[] questions;
    private void ReadJson02()
    {
        // 获取json文件中所有的文字(json文件需要是 UTF8 编码)
        string data = File.ReadAllText(Application.streamingAssetsPath + "/Question.json", System.Text.Encoding.UTF8);
        // 将文字转换为本类中的字段
        JsonUtility.FromJsonOverwrite(data, this);
        // 将读取的内容打印到控制台
        string str = "Json 文件读取成功,内容如下:\n\n";
        for (int i = 0; i < questions.Length; i++)
        {
            str += "问题:" + questions[i].title + "\n";
            str += "A、" + questions[i].A + "\n";
            str += "B、" + questions[i].B + "\n";
            str += "C、" + questions[i].C + "\n";
            str += "D、" + questions[i].D + "\n";
            str += "答案:" + questions[i].answer + "\n\n";
        }
        print(str);
    }
    // 写入 json
    private void WriteJson()
    {
        // 创建第一个问题
        AloneQuestion aq1 = new AloneQuestion();
        // 为问题中的每个变量赋值
        aq1.title = "《滕王阁序》是谁写的";
        aq1.A = "李白";
        aq1.B = "杜甫";
        aq1.C = "陈世美";
        aq1.D = "西门庆";
        aq1.answer = "A";

        // 创建第二个问题
        AloneQuestion aq2 = new AloneQuestion();
        // 为问题中的每个变量赋值
        aq2.title = "请选出《西游记》中的主要人物";
        aq2.A = "吴承恩";
        aq2.B = "罗贯中";
        aq2.C = "张无忌";
        aq2.D = "郭富城";
        aq2.answer = "C";

        // 将所有问题添加“合集”中
        AllQuestion allQ = new AllQuestion();
        allQ.questions = new AloneQuestion[2];
        allQ.questions[0] = aq1;
        allQ.questions[1] = aq2;

        // 将数据转换为 json 格式
        string str = JsonUtility.ToJson(allQ);

// 如果路径不存在就生成路径
if (!Directory.Exists(Application.streamingAssetsPath)) { Directory.CreateDirectory(Application.streamingAssetsPath); } // json 数据要存储的路径 string path = Application.streamingAssetsPath + "/Question.json"; // 保存 json 文件 File.WriteAllText(path, str); print("Json 文件写入成功"); } } // 所有“问题”的合集(注意:一定要序列化,不序列化读不出来) [Serializable] public class AllQuestion { public AloneQuestion[] questions; } // 一个完整的“问题”类(注意:一定要序列化,不序列化读不出来) [Serializable] public class AloneQuestion { public string title; public string A; public string B; public string C; public string D; public string answer; }

完整的 json(如果下载了unityPackage 该 json 会自动生成)

{
    "questions":[
        {
        "title":"《滕王阁序》是谁写的",
        "A":"李白",
        "B":"杜甫",
        "C":"陈世美",
        "D":"西门庆",
        "answer":"A"
        },
        {
        "title":"请选出《西游记》中的主要人物",
        "A":"吴承恩",
        "B":"罗贯中",
        "C":"张无忌",
        "D":"郭富城",
        "answer":"C"
        }
    ]
}

 

最后:提供一个 UnityPackage 供测试使用(点击下载

  UnityPackage操作说明:

    W:生成 Json 文件;

    R:使用方法一,读取 Json 并打印到控制台;

    空格:使用方法二,读取 Json 并打印到控制台;

posted on 2022-12-28 19:58  考拉宝贝  阅读(1055)  评论(0编辑  收藏  举报

导航