Turn JSON string into Custom objects in Unity

ยท 1 min read
Turn JSON string into Custom objects in Unity

Store user's data or game's state in JSON, or fetch data from api call in game, Luckily, Unity does provide the JsonUtility to rescue, which can easily convert a json string into a custom class or struct. However, Unity's JsonUtility does only support objects as top level nodes, which means we need a wrapper to received a pure list, take a look at the following example:

Example json:

{
  "items": [
    {
      "playerId": 1,
      "name": "Andrew"
    },
    {
      "playerId": 2,
      "name": "Ben"
    }
  ]
}

Example script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;


[System.Serializable]
public class PlayerData {
  public int playerId;
  public string name;
}

[System.Serializable]
public class PlayerDataList {
  public PlayerData[] items;
}

public class GetRemoteUsers : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(getRemoteUser());
    }

    private IEnumerator getRemoteUser()
    {
        UnityWebRequest uwr = UnityWebRequest.Get("https://mocki.io/v1/8e552cba-c687-4794-9cc7-160cb914b1f9 ");
        yield return uwr.SendWebRequest();

        if (uwr.isNetworkError || uwr.isHttpError)
        {
            Debug.Log("Error While Sending: " + uwr.error);
        }
        else
        {
            Debug.Log("Received: " + uwr.downloadHandler.text);
            PlayerDataList data = JsonUtility.FromJson<PlayerDataList>(uwr.downloadHandler.text);
            Debug.Log("Users received " + data.items);
        }
    }
}

In this example, PlayerDataList is just wrapper, which only has one property named items contains all the users's real data. So unfortunately, we cant make use of the json array like this:

[
  {
    "playerId": 1,
    "name": "Andrew"
  },
  {
    "playerId": 2,
    "name": "Ben"
  }
]