- Home /
Unity json get data
I hav a json file for my game { "info": "About Us", "info_text": "Some Info about game...", "test": { "one": "one", "two": "two", "three": "three", "...": "...", ..... } }
so i create a class
public class LClass { public string info; public string info_text;
public TClass[] test; }
public class TClass { public string key; public string value; }
so how i can get the elements of "test"
help me pls ((
Answer by Bunny83 · Mar 31, 2019 at 02:34 AM
You created your "test" field in your class as an array. However your json does not contain an array but a single sub object. So the correct object mapping would look like this:
[System.Serializable]
public class LClass
{
public string info;
public string info_text;
public TClass test;
}
[System.Serializable]
public class TClass
{
public string one;
public string two;
public string three;
// [ ... ]
}
Note that Unity's JsonUtility is a pure object mapper. So you can not have dynamical object fields. If you need more flexibility you can use my SimpleJSON framework. It provides simple generic access to the json data.
JSONNode n = JSON.Parse(jsonText);
string info = n["info"].Value;
string info_text = n["info_text"].Value;
string one = n["test"]["one"].Value;
// or
foreach(var kvp in n["test"])
{
Debug.Log(kvp.Key + " = " + kvp.Value);
}
Thenk you for SympleJson
string one = n["test"]["one"].Value;
Answer by bagus123ind · Mar 31, 2019 at 02:45 AM
you can use JsonUtility.FromJson(YouJson)
i see the test value is array then first make sure structure json is correct and same with object you wan use to store data from json for "test" is should be
{
"info": "About Us",
"info_text": "Some Info about game...",
"test":[
{
"key":"yourKey",
"value":"yourValue"
}
]
}
and you can convert json to object like this
LClass lc = new LClass();
lc = JsonUtility.FromJson<LClass>(jsonData);
Debug.Log(lc.test[0].key); //to show key value from test index 0
if you dont know the correct strucuture json from your object you can make object manualy and convert to json to see what json for this model like this
LClass lc = new LClass();
lc.info = "About Us";
lc.info_text = "Some Info";
//make new TClass
TClass tc = new TClass();
tc.key = "1";
tc.value = "one";
lc.test = new List<TClass>();
lc.test.Add(tc);
Debug.Log(JsonUtility.ToJson(lc));
but i modify your class i use list to array test because is more fast to add value
[System.Serializable]
public class LClass {
public string info;
public string info_text;
public List<TClass> test;
}
[System.Serializable]
public class TClass {
public string key;
public string value;
}
Your answer
Follow this Question
Related Questions
Help me with this json code please 1 Answer
How to get a JSON string of a folder structure with c# in Unity3d 2 Answers
JsonUtility doesn't serialize nested mixed var 1 Answer
How to protect JSON file game data? 3 Answers
How can i get all of my users data on FireBase using Unity and RestClient json 1 Answer