首页 > 解决方案 > 我无法从 JSON 获取数据并且没有错误

问题描述

我正在尝试从 json 文件中仅获取一个对象,但不能。在检查器中,对象是空的,当我试图做某事时,该对象因为它是空的而得到空异常。我还尝试将我试图检索的对象放入列表中,但列表仍然是空的。我的错误在哪里?我的 Json 文件如下所示:

{
   "Dialogue": {
     "npcName": "John",
     "sentences": [
       {
         "text1": "Hello, come here",
         "text2": "How do you feel",
         "text3": " good bye!"
       }
     ]
 
   }
 
 }

这是我的代码:

 public TextAsset jsonScript;
 
     public Dialogue dialogue;
 
   void Start()
     {
  
         try
         {
 
             dialogue = JsonUtility.FromJson<Dialogue>(jsonScript.text);
             
         }
         catch (System.Exception error)
         {
 
             Debug.LogError(error);
         }
         
     }

对话课:

 [System.Serializable]
 public class Dialogue 
 {
     public string npcName;
     public string[] sentences;
 }

标签: c#jsonunity3d

解决方案


原始 json 中的句子是具有属性的复杂对象数组text1, text2, text3

你的 json 应该看起来像

{

     "npcName": "John",
     "sentences": [
       "Hello, come here", "How do you feel", " good bye!"
     ]
 
 }

适合Dialogue类型。


推荐阅读