- Home /
The question is answered, right answer was accepted
JSON Error : ArgumentException: JSON must represent an object type.
I am using the following script:
[System.Serializable]
public class Choice
{
public string choice;
public int votes;
}
[System.Serializable]
public class RootObject
{
public string question;
public string published_at;
public List<Choice> choices;
}
For the following JSON data:
{ "question": "Favourite programming language?", "published_at": "2015-08-05T08:40:51.620Z", "choices": [ { "choice": "Swift", "votes": 2048 }, { "choice": "Python", "votes": 1024 }, { "choice": "Objective-C", "votes": 512 }, { "choice": "Ruby", "votes": 256 } ] } ] And I am getting this Error message in console : ArgumentException: JSON must represent an object type. Please tell me what I am doing wrong.[
Answer by JDelekto · Apr 03, 2019 at 07:59 AM
At first glance, it looks like your JSON defines an array of RootObject objects, but you are trying to deserialize a single RootObject. If you are always getting an object with this JSON and only expect one object, you have two choices: a) remove the '[' and ']' array designator from the JSON string and deserialize as a RootObject or deserialize the JSON as a RootObject array (i.e. RootObject[]) and always take the first element of the array (if its length is not zero).
Note that (up to this point) the Unity's JsonUtility does not support an array as root object. It always expects an object as root element. If you want / need an array and want to use Unity's JsonUtility, you have to wrap your array in an object.
For more questions about Unity's JsonUtility, have a look at this SO question. If you're just looking for a way to easily read arbitrary json, have a look at my SimplyJSON framework
Interesting, I did not know Unity originally lacked the support for the collections. Normally I would not do what I suggested first, which was removing the square brackets but would ins$$anonymous$$d deserialize to a collection if the server was handing it off that way.
The SO link you provided was great in the context of Unity; however, it is good to know that they now support arrays in Unity's basic class.
I typically dislike wrapping the array as a property of some other object unless it was done with a generic so as to limit the number of classes in a project if I have several different serialized types.
Follow this Question
Related Questions
Hashtable as object literal serialization toJSON 0 Answers
Deserializing dictionary with 'Json.Net' for Unity returns a null object. 0 Answers
Parsing "complex" json 1 Answer
Serialization errors.. 0 Answers
use 3D models outside unity3d build ? 0 Answers