Unity中的Json字符串转换

Posted 生活在他方

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity中的Json字符串转换相关的知识,希望对你有一定的参考价值。

Unity访问网络API的时候,经常需要对Json字符串进行转换。Unity自带了一个Json转换的类JsonUtility。但是这个类功能不够强大,只能进行简单的转换。

其实Unity2020已经将Newtonsoft.Json内置进去了。

这个功能就比JsonUtility强大很多。使用的时候,添加一个引用即可。

例如下面这个Json字符串

用JsonUtility转换就无法把backResult转换出来,用Newtonsoft.Json就可以转换出正确结果。

例如下面代码:

using UnityEngine;
using Newtonsoft.Json;

public class JsonToObj : MonoBehaviour

    string jsonString = "\\"code\\":200,\\"msg\\":\\"成功\\",\\"backResult\\":\\"sessionID\\":\\"205ec794-767f-4fd7-ab6e-7d087989e990\\",\\"rtmpAddr\\":\\"rtmp://122.1.11.30:20002/live/205ec794-767f-4fd7-ab6e-7d087989e990?user=scth\\",\\"flvAddr\\":\\"http://122.1.11.30:20007/flv?port=20002&app=live&stream=205ec794-767f-4fd7-ab6e-7d087989e990&user=scth\\",\\"hlsAddr\\":\\"http://122.1.11.30:20007/hls/205ec794-767f-4fd7-ab6e-7d087989e990.m3u8?user=scth\\",\\"code\\":200,\\"info\\":\\"推送成功\\"";

    void Start()
    
        StreamingGet sg;

        sg = JsonUtility.FromJson<StreamingGet>(jsonString);

        Debug.Log("JsonUtility.FromJson");
        Debug.Log("code:" + sg.code);
        Debug.Log("backResult:" + sg.backResult);
        //Debug.Log("backResult.seesion:" + sg.backResult.sessionID);
        sg = JsonConvert.DeserializeObject<StreamingGet>(jsonString);
        Debug.Log("JsonConvert.DeserializeObject");
        Debug.Log("code:" + sg.code);
        Debug.Log("backResult:" + sg.backResult);
        Debug.Log("backResult.seesion:" + sg.backResult.sessionID);
    


运行后的效果

源码链接:https://gitee.com/BackFlowLake/UnityAndJson

以上是关于Unity中的Json字符串转换的主要内容,如果未能解决你的问题,请参考以下文章

我想将图像数据(Texture2D)转换为 Base64 字符串并存储在 Unity3D(C#)中的 JSON 文件中

如何在 Unity3D 中将类对象转换为 JSON 字符串?

Unity C#简单JSON到数组[重复]

Unity JsonUtility 没有正确地将字符串转换为对象

Unity 之 Excel表格转换为Unity用的文件格式 -- ScriptableObject,Json,XML 全部搞定

Unity如何使用从json字符串加载的变量作为更新部分的输入