Reputation: 180
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;
}
Upvotes: 1
Views: 514
Reputation: 90580
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.
Upvotes: 2
Reputation: 6870
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.
Upvotes: 2