首页 > 其他分享 >Unity3D_使用JsonUtility读取Json

Unity3D_使用JsonUtility读取Json

时间:2022-12-28 20:14:09浏览次数:70  
标签:Unity3D string json Json str questions JsonUtility public 读取

使用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 并打印到控制台;

标签:Unity3D,string,json,Json,str,questions,JsonUtility,public,读取
From: https://www.cnblogs.com/kao-la-bao-bei/p/17011089.html

相关文章

  • json和Java对象相互转换的四种方法
    第一种方法:原生解析首先要分析json的格式,这里首先是一个json对象(即JsonObject),里面还嵌套有一个json数组(即JsonArray),jsonarray里面又是一个json对象分析清楚那就可以进行......
  • python中resp.json()与json.loads(str)的区别
    resp=resquests.get(url)print(type(resp))#<class'requests.models.Response'>第一行代码使用requests库发送get请求,得到响应数据resp。第二行代码的输......
  • json断言
    在线程组>>添加>>断言>>json断言   ......
  • cpp jsoncpp serialize vector class into plain text file and deserialize from pla
    //model/book.h#pragmaonce#ifndef__book_h__#define__book_h__#include<iostream>usingnamespacestd;structbook{uint64_tidx;uint64_tid;......
  • json中的json.parseObject()方法和json.tojsonString()方法
    JSON.parseObject,是将Json字符串转化为相应的对象;JSON.toJSONString则是将对象转化为Json字符串。在前后台的传输过程中,Json字符串是相当常用的,这里就不多介绍其功能了,直接......
  • Json过滤
    varsettings=newJsonSerializerSettings{NullValueHandling=NullValueHandling.Ignore,ContractResolver=ShouldSe......
  • Unity3D学习之路
    1.准备C#的开发环境VS2015, Unity3D5.5.12.准备通信协议protobuf3.3.0 具体请参考:​​Protobuf3.3使用总结​​3.引入日志系统:​​C#日志系统Log4net使用总结​......
  • IOS中Json解析的四种方法
    作为一种轻量级的数据交换格式,json正在逐步取代xml,成为网络数据的通用格式。有的json代码格式比较混乱,可以使用此“http://www.bejson.com/”网站来进行JSON格式化校验(​​......
  • SQL Server JSON 转行 后转列
    1.使用ParseJsonFuncJSON转行USE[DataIntegration]GOCREATEFUNCTION[dbo].[ParseJsonFunc](@jsonnvarchar(max))RETURNS@hierarchytable(object_idintNOT......
  • GO json.Unmarshal() 解析不区分json字段的大小写
    GOjson.Unmarshal()解析不区分json字段的大小写demopackagemainimport( "encoding/json" "fmt")typeDemostruct{ ABDstring`json:"ABD"`}typeDem......