【问题标题】:I can't get data from JSON and there is no error我无法从 JSON 获取数据并且没有错误
【发布时间】:2021-10-01 16:48:37
【问题描述】:

我正在尝试从 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# json unity3d


    【解决方案1】:

    原始 json 中的句子是一组复杂对象,其属性为 text1, text2, text3

    你的 json 应该是这样的

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

    适合Dialogue 类型。

    【讨论】:

    • 非常感谢它的工作!但是我不明白为什么当我删除对象的名称(对话)时它会起作用?
    • @cançağlarkırıcı - 我认为答案是嵌套。在原始示例中,您有一个 JSON 对象,其中包含一个 Dialogue 对象,该对象包含一个字符串和一个数组。在 arynaq 的回答中,顶层对象已被移除,因此您所拥有的只是一个带有字符串和数组的对象,这符合 Dialogue 模型。
    • @suspicious_williams 哦,我现在明白了。谢谢你:)
    【解决方案2】:

    如果更改 JSON(如在 this answer 中)不是一种选择,那么您只需要一个类似的包装类

    [Serializable] 
    public class Root 
    {
        public Dialogue Dialogue; 
    }
    

    匹配您的原始 JSON 结构并执行

    dialogue = JsonUtility.FromJson<Root>(jsonScript.text).Dialogue; 
    

    改为。

    【讨论】:

    • 非常感谢。这也是一个非常合乎逻辑的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 2018-12-04
    相关资源
    最近更新 更多