Unity-Json数据解析

一、Json序列化(写入Json)

先附上Litjson.dll网盘地址(提取码:kkkk)https://pan.baidu.com/s/102xhr6O_LKeMmO7LJlLT0Q
命名空间引入

using UnityEngine;
using LitJson;
using System.IO;
using System.Text.RegularExpressions;
using System;
using System.Collections.Generic;

定义一个JsonInfo类,在对此类进行赋值之后进行json序列化操作

    /// <summary>
    /// 文件路径
    /// </summary>
    private string filePath = "C:/david.json";

    private void Start()
    {
        WriteJson();
    }
    /// <summary>
    /// Json信息类
    /// </summary>
    public class JsonInfo
    {
        public string userName;
    }

    /// <summary>
    /// Json写入
    /// </summary>
    private void WriteJson()
    {
        //初始化
        JsonInfo jsonInfo = new JsonInfo();
        jsonInfo.userName = "小华";

        StreamWriter sw = new StreamWriter(filePath);
        string json = JsonMapper.ToJson(jsonInfo);

        //转码 
        Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
        json = reg.Replace(json, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });

        //写入信息
        sw.Write(json);
        sw.Dispose();
        sw.Close();
    }

在Unity中运行后效果如下:
在这里插入图片描述

二、Json反序列化(读取Json)

相对于写入,读取应用的更加广泛一些,其作用和我之前分享的Unity与Excel表格交互类似。
包含了Json文件,字段、类、数组的读取(在C盘新建.json文件,用记事本或VS打开)。

{
	"userName":"小华",

	"userData":
	{
		"name":"小明",
		"age":25
	},

	"studentInfo":
	[
		{"name":"贝贝","age":20,"description":"爱吃萝卜和青菜"},
		{"name":"晶晶","age":16,"description":"喜欢健身"},
		{"name":"妮妮","age":29,"description":"她单身"}
	]
}
    /// <summary>
    /// Json读取
    /// </summary>
    private void ReadJson()
    {
        //文件流 读取
        StreamReader sr = new StreamReader(filePath);

        //读取的Json字符串
        string readContent = sr.ReadToEnd();

        //反序列化操作
        JsonInfo json = JsonMapper.ToObject<JsonInfo>(readContent);
        Debug.Log("userName:" + json.userName);
        Debug.Log("UserData name:" + json.userData.name);
        Debug.Log("UserData age:" + json.userData.age);
        Debug.Log("StudentInfo 0 name:" + json.studentInfo[0].name);
        Debug.Log("StudentInfo 0 age:" + json.studentInfo[0].age);
        Debug.Log("StudentInfo 0 descrption:" + json.studentInfo[0].description);
    }

    /// <summary>
    /// Json信息类
    /// </summary>
    public class JsonInfo
    {
        public string userName;
        public UserData userData;
        public List<StudentInfo> studentInfo;
    }

    /// <summary>
    /// 测试 用户数据类
    /// </summary>
    public class UserData
    {
        public string name;
        public int age;
    }

    /// <summary>
    /// 测试 学生信息类
    /// </summary>
    public class StudentInfo
    {
        public string name;
        public int age;
        public string description;
    }

最终在Unityi中运行发现正常读取json文件
在这里插入图片描述
完整代码如下:

using UnityEngine;
using LitJson;
using System.IO;
using System.Text.RegularExpressions;
using System;
using System.Collections.Generic;

public class JsonTest : MonoBehaviour
{
    /// <summary>
    /// 文件路径
    /// </summary>
    private string filePath = "C:/david.json";

    private void Start()
    {
        //WriteJson();
        ReadJson();
    }

    /// <summary>
    /// Json写入
    /// </summary>
    private void WriteJson()
    {
        //初始化
        JsonInfo jsonInfo = new JsonInfo();
        jsonInfo.userName = "小华";

        StreamWriter sw = new StreamWriter(filePath);
        string json = JsonMapper.ToJson(jsonInfo);

        //转码 
        Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
        json = reg.Replace(json, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });

        //写入信息
        sw.Write(json);
        sw.Dispose();
        sw.Close();
    }

    /// <summary>
    /// Json读取
    /// </summary>
    private void ReadJson()
    {
        //文件流 读取
        StreamReader sr = new StreamReader(filePath);

        //读取的Json字符串
        string readContent = sr.ReadToEnd();

        //反序列化操作
        JsonInfo json = JsonMapper.ToObject<JsonInfo>(readContent);
        Debug.Log("userName:" + json.userName);
        Debug.Log("UserData name:" + json.userData.name);
        Debug.Log("UserData age:" + json.userData.age);
        Debug.Log("StudentInfo 0 name:" + json.studentInfo[0].name);
        Debug.Log("StudentInfo 0 age:" + json.studentInfo[0].age);
        Debug.Log("StudentInfo 0 descrption:" + json.studentInfo[0].description);
    }

    /// <summary>
    /// Json信息类
    /// </summary>
    public class JsonInfo
    {
        public string userName;
        public UserData userData;
        public List<StudentInfo> studentInfo;
    }

    /// <summary>
    /// 测试 用户数据类
    /// </summary>
    public class UserData
    {
        public string name;
        public int age;
    }

    /// <summary>
    /// 测试 学生信息类
    /// </summary>
    public class StudentInfo
    {
        public string name;
        public int age;
        public string description;
    }
}
  • 6
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Unity中,使用Newtonsoft.Json解析JSON数据是一种常见的做法。你可以将Newtonsoft.Json.dll文件包含在你的项目中,然后使用它来对JSON数据进行解析。这个程序包不需要与jillejr.newtonsoft.json-for-unity软件包一起使用,因为它提供了自己的Newtonsoft.Json实现。你可以在Unity的生态系统中找到许多关于Newtonsoft.Json的分支和变体,但是你可以选择使用该程序包提供的版本。如果你需要使用Newtonsoft.Json的使用教程,你可以参考CSDN上的一个文章,链接如下:。这个教程将向你展示如何在Unity中使用Newtonsoft.Json解析JSON数据。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Newtonsoft.Json-for-Unity.Converters:Newtonsoft.Json的常见Unity类型的转换器。 与jilleJrNewtonsoft....](https://download.csdn.net/download/weixin_42112894/18775229)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Unity版Newtonsoft.Json](https://download.csdn.net/download/weixin_38239050/14803540)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [UnityIK人体骨骼反向动力学系统插件 Final IK 2.2](https://download.csdn.net/download/mayzhengxi/88262273)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

StubbrnStar

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

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

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

打赏作者

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

抵扣说明:

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

余额充值