obsidian/笔记文件/2.笔记/UnityEngine.JsonUtility.FromJson()的坑.md
2025-03-26 00:02:56 +08:00

2.0 KiB
Raw Permalink Blame History

#unity/日常积累

UnityEngine命名空间下的Json解析APIJsonUtility类。这个得用法应该和LitJson.dll中差不多具体没用深入研究应该算是简略版的Litjson一般开发使用够用了。

今天使用的时候发现了一些问题,记录一下,防止以后遇到还踩坑。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text;
using System;
 
public class JsonTools : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        TextAsset json = Resources.Load<TextAsset>("PanelMessageInfo");
 
        MessageStructRoot pm = JsonUtility.FromJson<MessageStructRoot>(json.text);
        Debug.Log(pm.MessageList[0].picturePath + "====================>" + pm.MessageList[1].zhengwen);
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }
}
[Serializable]
public class SetMessageStruct
{
    /// <summary>
    /// 
    /// </summary>
    public string zhengwen;
    /// <summary>
    /// 
    /// </summary>
    public string picturePath;
}
 
[Serializable]
public class MessageStructRoot
{
    public List<SetMessageStruct> MessageList ;
 
    
}

打印输出

{
"MessageList": [
{ "zhengwen":"John" , "picturePath":"D/Doe" },
{ "zhengwen":"Anna" , "picturePath":"D/Smith" },
{ "zhengwen":"Peter" , "picturePath":"D/Jones" }
]
}
主要问题就出在这个[Serializable]之前使用LitJson时我要是没记错的话是不需要加这个序列化标签的但是使用JsonUtility.FromJson进行解析如果不加[Serializable]无法解析出List<T>也就是Json中[...]中的内容。

会报NullReferenceException: Object reference not set to an instance of an object
JsonTools.Start () (at Assets/Scripts/JsonTools/JsonTools.cs:15)

错误即无法解析出List<T>打断点也可看到MessageStructRoot pm = JsonUtility.FromJson<MessageStructRoot>(json.text);解析完成后pm中只有一个为null的MessageList。