Hello there!
Here’s a bit of background information:
I’m making a GET request to retrieve JSON data, and I’m trying to store that data into a structure of classes. Printing the retrieved data to the console works, but assigning it to the classes does not (it remains empty in the inspector after the request.)
I’ve split the code into two sections.
1. Makes the web request and attempts to store the data into a class structure.
2. The current class structure
Here is a link to the JSON Data I’m using.
public class WebRequestTest : MonoBehaviour
{
public string uri = "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo";
public RootObject rootObj;
void Start()
{
StartCoroutine(GetRequest(uri));
}
IEnumerator GetRequest(string uri)
{
UnityWebRequest req = UnityWebRequest.Get(uri);
yield return req.SendWebRequest();
Debug.Log(req.downloadHandler.text);
rootObj = JsonUtility.FromJson<RootObject>(req.downloadHandler.text);
}
}
Below is the structure for my classes so far. I’m imagining that the issue might be with TimeSeries.dataPeriods.
(TLDR: I wasn’t sure whether to use an array, a list, or something else; but I settled on a list.)
[Serializable]
public class RootObject
{
public MetaData metaData;
public TimeSeries timeSeries;
}
[Serializable]
public class MetaData
{
public string Information;
public string Symbol;
public string LastRefreshed;
public string OutputSize;
public string TimeZone;
}
[Serializable]
public class TimeSeries
{
public List<DataPeriod> dataPeriods;
}
[Serializable]
public class DataPeriod
{
public Data data;
}
[Serializable]
public class Data
{
public string Open;
public string High;
public string Low;
public string Close;
public string Volume;
}
You may have noticed in the Data class that I stored all the numeric data as strings. I thought I’d need to store them this way at first because they are coming from JSON and then convert them later when needed. (Perhaps there is a more elegant way to handle this?)
Final questions:
1. Am I handling comma separated objects the right way by using a list or should I be doing something else?
2. Does anything stand out as to whats preventing the data from being assigned into the RootObject class?
3. If you have any insights about what would be a good way to handle converting the numbers to ints/floats when the class is created, I would love to hear it!
Thank you so much for reading this! I’m going to keep working on this and will post an update when I can.