I'm trying to use Json to hold game dialog in a text asset file. I've tried to make a barebones project to test this and it is failing with the Error Message: ArgumentException: JSON must represent an object type.
I have a class called LineData which has a few properties each line of dialog contains. In the Json there are just two lines for now. When I import and parse it to try and make a reference to one of the lines of dialog it fails.
Here is all the code:
dialogJson.JSON:
[
{
"lineID": "BEDROOM_DAVE_0001",
"lineDialog": "Yaawwn, up i get for another fun packed day.",
"lineDuration": 3
},
{
"lineID": "BEDROOM_DAVE_0002",
"lineDialog": "Well I think I need a cigarette before I get to work!",
"lineDuration": 3
}
]
LineData.cs
using System;
[Serializable]
public class LineData
{
public string lineID;
public string lineDialog;
public float lineDuration;
}
GameController.cs
using UnityEngine;
public class GameController : MonoBehaviour
{
TextAsset Dialog_Data;
private void Start()
{
Dialog_Data = Resources.Load<TextAsset>("txt/dialogJson");
LineData line1 = JsonUtility.FromJson<LineData>(Dialog_Data.text);
Debug.Log("line 1 dialog = " + line1.lineDialog);
}
}
NOTE: I read here (https://answers.unity.com/questions/1503047/json-must-represent-an-object-type.html) that Unity "can't parse if the json consists of an array of objects". But I don't understand his explanation on how to get around this. Thanks
EDIT: I now have it without error, but the debug message is just empty didnt seem to get any data) . Here is the json now after the edits:
{ "LineData":
[
{
"lineID": "BEDROOM_DAVE_0001",
"lineDialog": "Yaawwn, up i get for another fun packed day.",
"lineDuration": 3
},
{
"lineID": "BEDROOM_DAVE_0002",
"lineDialog": "Well I think I need a cigarette before I get to work!",
"lineDuration": 3
}
]
}
I've also altered the GameController.cs like this (but now it says Index is outside array bounds:
public class GameController : MonoBehaviour
{
TextAsset Dialog_Data;
private void Start()
{
LineData[] lines = new LineData[2];
Dialog_Data = Resources.Load<TextAsset>("txt/dialogJson");
lines = JsonUtility.FromJson<LineData[]>(Dialog_Data.text);
Debug.Log("line 1 dialog = " + lines[0].lineDialog);
}
}
lines = new LineData[2];
, then load data into those slots withlines = JsonUtility...
. C# assignment does not work that way. It doesn't "write into" an existing array - it gives you a whole new array. So the first empty array you created is thrown out as garbage, and you might as well have never created it at all. You can write an individual index into an array withlines[0] = whatever
, but when you assign tolines
itself with no brackets you're always just replacing the old reference with a new one. \$\endgroup\$