- Home /
Need Help with Json File
I don't know how to get data from a json file in unity. My json file looks something like this [{ "b": "0.070", "e": null, "a": null, "t": null, "_": null, "i": null, "m": null }, { "b": "28.932", "e": null, "a": null, "t": null, "_": null, "i": null, "m": null },
I have looked into a lot of tutorials but I'm still not getting it
Answer by Ymrasu · Mar 01, 2019 at 03:52 AM
First, for Unity's JsonUtility to read the Json file, the array needs to be wrapped in a single object, kinda like this:
{ "d" : [{ "b": "0.070", "e": null, "a": null, "t": null, "_": null, "i": null, "m": null }, { "b": "28.932", "e": null, "a": null, "t": null, "_": null, "i": null, "m": null },
Then you need to make classes to match the objects of the json, for this file it would be similar to this:
[System.Serializable]
public class Database
{
public Data[] d;
}
[System.Serializable]
public class Data
{
public float b;
public float e;
public float a;
public float t;
public float _;
public float i;
public float m;
}
The variable names and types need to match. (You'll need to change the data types, I can't tell what data types you want for those nulls). Then you can finally load the Json file and use the JsonUtility.
// put your json file under /Assets/StreamingAssets/
string filePath = Path.Combine(Application.streamingAssetsPath, "data.json");
// if file was found
if (File.Exists(filePath)) {
// read json file
string dataAsJson = File.ReadAllText(filePath);
// parse into object
Database database = JsonUtility.FromJson<Database>(dataAsJson);
// test (remove these debugs)
Debug.Log(database.d[0].b);
Debug.Log(database.d[1].b);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612192711im_/https://answers.unity.com/themes/thub/images/avi.jpg)