I have encountered a problem while trying to parse a JSON string in Unity. I wrote a API in C# ASP.NET to communicate with a database. When I try to parse the JSON string from my get request gives me the error message: ArgumentException: JSON must represent an object type..
The error only occurs when I try to parse a JSON string with several objects. When I try to make a Get request that only returns one object it works. I have tried to make a class for the object in the Unity script and a class with a list to store the objects in. I am using profileList = JsonUtility.FromJson(responseText);
This is my JSON string: [ { "id": 1, "name": "name1", "avatar": "avatar1", "theme": "jungle" }, { "id": 2, "name": "name2", "avatar": "avatar2", "theme": "space" }, { "id": 3, "name": "name3", "avatar": "avatar3", "theme": "jungle" }, { "id": 4, "name": "name4", "avatar": "avatar4", "theme": "space" } ]
public class ProfileAPI : MonoBehaviour
{
public class Profile
{
public int id;
public string name;
public string avatar;
public string theme;
}
public class ProfileList
{
public Profile[] profileList;
}
public ProfileList profileList = new ProfileList();
void Start()
{
StartCoroutine(GetRequest("https://localhost:7166/memory/Profiles"));
}
IEnumerator GetRequest(string url)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
{
yield return webRequest.SendWebRequest();
if (webRequest.result == UnityWebRequest.Result.ConnectionError ||
webRequest.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError("Error: " + webRequest.error);
}
else
{
string responseText = webRequest.downloadHandler.text;
Debug.Log(responseText);
profileList = JsonUtility.FromJson<ProfileList>(responseText);
}
}
}
}