How To Deserialize Json Data Into List?
So I'm trying to deserialize a json file into a database in Unity. The json file looks like this:
[
{
"ID": 0,
"Title": "Peastol",
"Slug": "peastol",
"BurstCount": 1,
"TypeOfProjectile": "Pea",
"RateOfFire": 3,
"Inaccuracy": 3,
"XOffset": 10.5,
"YOffset": 3.2,
"PrefabXOffset": 8,
"PrefabYOffset": -0.6
},
{
"ID": 1,
"Title": "Lemonade Launcher",
"Slug": "lemonade_launcher",
"BurstCount": 1,
"TypeOfProjectile": "Lemonade",
"RateOfFire": 5,
"Inaccuracy": 5,
"XOffset": 8.45,
"YOffset": 2.0,
"PrefabXOffset": 17.90,
"PrefabYOffset": -0.6
},
{
"ID": 2,
"Title": "Pepper Thrower",
"Slug": "pepper_thrower",
"BurstCount": 1,
"TypeOfProjectile": "Pepper",
"RateOfFire": 0.5,
"Inaccuracy": 0,
"XOffset": 14.5,
"YOffset": 2.4,
"PrefabXOffset": 8,
"PrefabYOffset": 2.8
}
]
and I'm trying to deserialize it like this:
public List<Weapon> weaponDatabase = new List<Weapon>();
weaponDatabase = JsonUtility.FromJson<List<Weapon>>(@"Assets\JSON Data\Weapons");
I get a "JSON Parse Error". Can anyone help me out with this? I can't find a solution online.
I'm in a similar boat, but one thing I see is you might want to make the path a variable and put it in.
Answer by Avanatra · Apr 11, 2018 at 08:35 AM
its been a long time, but anyway you need to put a container to your Json object.
{
weaponList : [
{
"ID": 0,
"Title": "Peastol",
"Slug": "peastol",
"BurstCount": 1,
"TypeOfProjectile": "Pea",
"RateOfFire": 3,
"Inaccuracy": 3,
"XOffset": 10.5,
"YOffset": 3.2,
"PrefabXOffset": 8,
"PrefabYOffset": -0.6
},
{
"ID": 1,
"Title": "Lemonade Launcher",
"Slug": "lemonade_launcher",
"BurstCount": 1,
"TypeOfProjectile": "Lemonade",
"RateOfFire": 5,
"Inaccuracy": 5,
"XOffset": 8.45,
"YOffset": 2.0,
"PrefabXOffset": 17.90,
"PrefabYOffset": -0.6
},
{
"ID": 2,
"Title": "Pepper Thrower",
"Slug": "pepper_thrower",
"BurstCount": 1,
"TypeOfProjectile": "Pepper",
"RateOfFire": 0.5,
"Inaccuracy": 0,
"XOffset": 14.5,
"YOffset": 2.4,
"PrefabXOffset": 8,
"PrefabYOffset": 2.8
}
]
}
then create a class with a field called weaponList
[System.Serializable]
public class WeaponListObject{
public List<Weapon> weaponList;
}
then serialize it like that
public WeaponListObject weaponDatabase;
weaponDatabase = JsonUtility.FromJson<WeaponListObject>(@"Assets\JSON Data\Weapons");
i did not test it, but you need to implement something like this
Your answer
Follow this Question
Related Questions
Json doesnt work in android (unity) 0 Answers
Create a list of BaseType where different supertypes are contained. 0 Answers
Realtime data with JSON,Realtime JSON updates 0 Answers
How to read a nested Array Json File in unity 3d? 0 Answers
save one big json string vs multi seperate json strings in playerprefs 0 Answers