UnityEngine.JsonUtility.FromJson()的坑.md 2.0 KB

#unity/日常积累

UnityEngine命名空间下的Json解析API,JsonUtility类。这个得用法应该和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。