JsonUtility and Arrays - JSON must represent an object type.
This question looks like it's been asked several times, but i see multiple results in the process and testing my way through them all i keep ending up with the 'JSON must represent an object type' error.
I'm currently making a journal feature within my game. The basic flow should be that the player finds journals throughout the game world. These journals are picked up and added to a journal inventory. The player can access the journal inventory and click on the different entries to read the different journals.
My code is as below.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class JournalList : MonoBehaviour {
private string filename;
static readonly string JOURNAL_DATA = "TestEntries.json";
void Start () {
filename = Path.Combine(Application.streamingAssetsPath, JOURNAL_DATA);
string jsonFromFile = File.ReadAllText(filename);
JournalData journalData = JournalData.CreateFromJSON(jsonFromFile);
Debug.Log(journalData.journal);
JournalDataList list = JournalDataList.CreateFromJSON(jsonFromFile);
Debug.Log(list.items[0].journal);
}
}
[System.Serializable]
public class JournalData
{
public int index;
public string content;
public string journal;
public static JournalData CreateFromJSON(string jsonString)
{
return JsonUtility.FromJson<JournalData>(jsonString);
}
}
[System.Serializable]
public class JournalDataList
{
public JournalData[] items;
public static JournalDataList CreateFromJSON(string jsonString)
{
return JsonUtility.FromJson<JournalDataList>(jsonString);
}
}
The Json is saved as below:
[
{"index":1,"content":"Day One","journal":"It was a dark and stormy night."},
{"index":2,"content":"Day Two","journal":"Still dark and stormy."}
]
When i run this i get:
ArgumentException: JSON must represent an object type.
UnityEngine.JsonUtility.FromJson[JournalData] (System.String json) (at C:/buildslave/unity/build/artifacts/generated/bindings_old/common/JSONSerialize/JsonUtilityBindings.gen.cs:25)
JournalData.CreateFromJSON (System.String jsonString) (at Assets/Scripts/JournalData.cs:10) (the ' return JsonUtility.FromJson<JournalData>(jsonString);' line)
JournalList.Start () (at Assets/Scripts/JournalList.cs:22) (the 'JournalData journalData = JournalData.CreateFromJSON(jsonFromFile);' line)
I originally had this set up for a single journal entry and that works fine. It's only when i've moved it to being an array that i've started to have issues. Could someone point me in the right direction please? Thanks in advance.
Your answer
Follow this Question
Related Questions
Custom Class - What did I do wrong? 0 Answers
Null Exception while serialize json string into txt file 0 Answers
Difference between serialization and saving data 2 Answers
Json to array of objects C# 1 Answer