简体   繁体   中英

I can't get data from JSON and there is no error

i am trying get just one object from json file but can't. In the inspector, object is empty and when im trying to do something whit that object im getting null exception because of its empty. I also tried putting the object I was trying to retrieve in a list, but the list was still empty. Where is my mistake? my Json file look like this:

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

And this is my code:

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

Dialogue class:

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

Sentences in your original json is an array of complex objects with properties text1, text2, text3

Your json should look like

{

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

To fit the Dialogue type.

If changing the JSON (like in this answer ) is not an option then you would simply need one more wrapper class like

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

to match your original JSON structure and do

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

instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM