Search code examples
c#jsonunity-game-engineparsinglitjson

Parsing JSON from API URL in Unity via C#


I am trying to parse some data that is in a JSON Array so that I can use it in my project. The values are used in plotting functions for visualizing orbits, I have completed literally everything for the project besides this task. To do the parse the JSON I am attempting to use LitJSon but am having no luck. If anyone can provide some insight as to how I should do this it would be greatly appreciated.

Here is the JSON format that I have:

URL: https://5289daa5c202.ngrok.io/api/tle

[
    {
        "SatNum": "47757",
        "Epoch": "21076.58335648",
        "MMotDeriv": "-.01183622",
        "inclination": "53.0445",
        "RAAN": "118.1488",
        "Eccentricity": "0001096",
        "ArgPerigee": "64.2393",
        "MAnomaly": "229.2271",
        "MMotion": "15.76357572"
    }, {
        "SatNum": "47758",
        "Epoch": "21076.83334491",
        "MMotDeriv": "-.01182939",
        "inclination": "53.0463",
        "RAAN": "116.9104",
        "Eccentricity": "0001165",
        "ArgPerigee": "60.1537",
        "MAnomaly": "211.8085",
        "MMotion": "15.75727878"
    }
]

Solution

  • To fetch data from a server use the new UnityWebRequest class. example:

    using UnityEngine;
    using UnityEngine.Networking;
    using System.Collections;
    
    public class MyBehaviour : MonoBehaviour
    {
        public string json;
        void Start()
        {
            StartCoroutine(GetText());
        }
    
        IEnumerator GetText()
        {
            using (UnityWebRequest www = UnityWebRequest.Get("http://www.my-server.com"))
            {
                yield return www.Send();
    
                if (www.isNetworkError || www.isHttpError)
                {
                    Debug.Log(www.error);
                }
                else
                {
                    // Show results as text
                    json = www.downloadHandler.text;
    
                    // Or retrieve results as binary data
                    byte[] results = www.downloadHandler.data;
                }
            }
        }
    }
    

    You can then use JsonUtility to convert it to c# class you have to make an object class with variable and use the json data as constructor.

    example:

    using UnityEngine;
    
    [System.Serializable]
    public class PlayerInfo
    {
        public string name;
        public int lives;
        public float health;
    
        public static PlayerInfo CreateFromJSON(string jsonString)
        {
            return JsonUtility.FromJson<PlayerInfo>(jsonString);
        }
    
        // Given JSON input:
        // {"name":"Dr Charles","lives":3,"health":0.8}
        // this example will return a PlayerInfo object with
        // name == "Dr Charles", lives == 3, and health == 0.8f.
    }