Getting data from json from API request

Hey everyone! I’ve been trying to get the data from API in a form of json and get some values from it. The json looks like this:

[{
        "timestamp": "2022-07-07 12:50:44",
        "id": 11222290496,
        "location": {
            "exact_location": 0,
            "id": 60603,
            "country": "DE",
            "latitude": "52.548",
            "indoor": 0,
            "altitude": "55.3",
            "longitude": "13.42"
        },
        "sensor": {
            "sensor_type": {
                "id": 14,
                "manufacturer": "Nova Fitness",
                "name": "SDS011"
            },
            "id": 72573,
            "pin": "1"
        },
        "sensordatavalues": [{
                "id": 24949825211,
                "value": "6.75",
                "value_type": "P1"
            }, {
                "id": 24949825213,
                "value": "4.28",
                "value_type": "P2"
            }
        ],
        "sampling_rate": null
    }, {
        "timestamp": "2022-07-07 12:48:17",
        "id": 11222265122,
        "location": {
            "exact_location": 0,
            "id": 60603,
            "country": "DE",
            "latitude": "52.548",
            "indoor": 0,
            "altitude": "55.3",
            "longitude": "13.42"
        },
        "sensor": {
            "sensor_type": {
                "id": 14,
                "manufacturer": "Nova Fitness",
                "name": "SDS011"
            },
            "id": 72573,
            "pin": "1"
        },
        "sensordatavalues": [{
                "id": 24949766720,
                "value": "5.25",
                "value_type": "P1"
            }, {
                "id": 24949766738,
                "value": "3.80",
                "value_type": "P2"
            }
        ],
        "sampling_rate": null
    }
]

The C# script for this json:

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

[Serializable]
public class Root
{
    public Root2[] root2;
    public List<Root> root;

}

[Serializable]
public class Root2
{
    public Location location;
    public Sensor sensor;
    public object sampling_rate;
    public string timestamp;
    public object id;
    public List<Sensordatavalue> sensordatavalues;
}

[Serializable]
public class Location
{
    public string country;
    public string latitude;
    public int exact_location;
    public int id;
    public int indoor;
    public string altitude;
    public string longitude;
}

[Serializable]
public class Sensor
{
    public SensorType sensor_type;
    public string pin;
    public int id;
}

[Serializable]
public class Sensordatavalue
{
    public string value_type;
    public string value;
    public object id;
}

[Serializable]
public class SensorType
{
    public string manufacturer;
    public string name;
    public int id;
}

And the script to get the API response and values from json:

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


public class jsonController : MonoBehaviour
{
    public string jsonURL;
    private Root jsnData;
    // Start is called before the first frame update
    void Start()
    {
        //processJsonData(jsonURL);
        StartCoroutine(getData());
    }

    IEnumerator getData()
    {
        Debug.Log("Processing...");

        WWW _www = new WWW(jsonURL);
        yield return _www;
        if(_www.error == null)
        {
            processJsonData("{\"data\":" + _www.text + "}");  
        }
        else
        {
            Debug.Log("Something's wrong");
        }
    }


    private void processJsonData(string _url)
    {
        Root2 jsnData = JsonUtility.FromJson<Root2>(_url); 
        Debug.Log("Json dat: " + jsnData.id);

       
        foreach(Root2 item in jsnData.data)
        {
            Debug.Log("id: " + item.id);
        }
    }
}

The issue is that jsnData.data in foreach is highlighted and the VS shows error “Root2 does not contain a definition for data”

I tried implementing the method (foreach) from this question:

Thank you in advance

You shouldn´t just copy code that you don´t understand. Your class “Root2” has no list or array with the name “data”, so the property just doesn´t exist, that´s why it is highlighted.

In your case it has to be:

 Root jsnData = JsonUtility.FromJson<Root>(_url);
Debug.Log("Json dat: " + jsnData.id);
      
foreach(Root2 item in jsnData.root2)
{
    Debug.Log("id: " + item.id);
}

And why do you have a list of roots in your root class ? Do you really need that list ?

Btw. your array and your list are named in singular they should be named in plural, otherwise this leads into confusions and your class naming should follow the pascal naming convention (JsonController), as well as your methods.

Note in the example you shared, “data” is the JSON root element, I don’t see a root element in your JSON

1 Like

Thank you! You pointed to the right spot.
I add{"data": }
to the json from the API response to make it readable by Unity, since it’s not supporting arrays.

I changed the first 2 classes for Root script. Now it looks like this.

[Serializable]
public class Root
{
    public Datum[] data;
}

[Serializable]
public class Datum
{
    public string timestamp;
    public object id;
    public Location location;
    public Sensor sensor;
    public List<Sensordatavalue> sensordatavalues;
    public object sampling_rate;
}

I also changed the second script:

private void processJsonData(string _url)
    {
        Root jsnData = JsonUtility.FromJson<Root>(_url);
        Debug.Log("Json data: " + jsnData.data);

        foreach(Datum item in jsnData.data)
        {
            Debug.Log("id: " + item.timestamp); //timestamp
        }

    }

And now it returns timestamp value in the console.

However, when I try to get id by calling Debug.Log("id: " + item.id); the console doesn’t return id value

I think you have the same problem as the person in the link you posted.

Try to change the data type of “id” in your Datum class from object to int:
public int id;

1 Like

It worked, thank you!

Althought the returned value for some reason was negative, I used Math.Abs() to make it positive.