-1

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);

                

            }
        }
    }
}
  • Does this answer your question? [Unity C# JsonUtility is not serializing a list](https://stackoverflow.com/questions/41787091/unity-c-sharp-jsonutility-is-not-serializing-a-list) – BugFinder May 18 '23 at 09:11
  • An instance of `ProfileList` is an object, not an array. The JSON you have is an array of `Profile`, so the type you want to deserialize it to would be `Profile[]` – Xerillio May 18 '23 at 09:14
  • Allright, I have tried some variations of this. I tried to serialize it to a profile array like this: Profile[] profiles = new Profile[10]; profiles = JsonUtility.FromJson(responseText); and I also tried to serialize it to a List of Profiles – stevenWalters May 18 '23 at 09:20
  • Your root JSON container is an **array** not an object, which `JsonUtility` does not support. See [Serialize and Deserialize Json and Json Array in Unity](https://stackoverflow.com/a/36244111/3744182) for workarounds. Or use Json.NET which does support root arrays. It's now officially ported to Unity and may now be obtained directly from Unity from here: [com.unity.nuget.newtonsoft-json@3.0](https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@3.0/manual/index.html). Just add `com.unity.nuget.newtonsoft-json` via the package manager. – dbc May 18 '23 at 14:50

1 Answers1

1

So when trying to convert a JSON string to a C# object in Unity, you have to keep 3 things in mind.

  1. Ensure you receive a JSON object and not an array. For Example

{"profileList" : [ { "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" } ]}

  1. Make sure all the classes that are linked to the JSON to C# conversation in your case Profile and ProfileList have a [Serializable] attribute on top of the class. For Example:

    [Serializable]
    public class Profile
    {
        public int id;
        public string name;
        public string avatar;
        public string theme;
    }
    
    [Serializable]
    public class ProfileList
    {
        public Profile[] profileList;
    }
    
    
  2. Name of the variables should be the same as in the JSON string you are parsing JSON.

We can deserialise JSON array to C#[](C# array) or to a List<T>(generic list). Now if you use the above example it should parse with the given classes without any issues.

Following what you are doing will result in an error from Unity saying something along the lines of "JSON object is not valid" or "JSON string does not have a valid object". I am not sure which exception/error you will get but you will get one for sure.