Hi everyone i try to use JSON.NET with my json files. I want a collection of objects to iterate through and take the information i want.
Here's my json files [EDIT FOR EXPLANATION] I have a collection of launchers (3 here but i will add more later with the same attributs). I need to be able to iterate through all of them and know if they are unlock or not. If they are unlock i'll need to take their attribut for some calcul.
{ "Canon":{ "Unlock": true, "FireRate": 0, "IsRotate": false, "RotateSpeed": 0, "NumberOfBullets": 0 }, "Rotator":{ "Unlock": false, "FireRate": 0, "IsRotate": true, "RotateSpeed": 0, "NumberOfBullets": 0 }, "Back":{ "Unlock": false, "FireRate": 0, "IsRotate": false, "RotateSpeed": 0, "NumberOfBullets": 0 } } Here's my classes for mapping
[System.Serializable] public class Canon { public bool Unlock { get; set; } public int FireRate { get; set; } public bool IsRotate { get; set; } public int RotateSpeed { get; set; } public int NumberOfBullets { get; set; } } [System.Serializable] public class Rotator { public bool Unlock { get; set; } public int FireRate { get; set; } public bool IsRotate { get; set; } public int RotateSpeed { get; set; } public int NumberOfBullets { get; set; } } [System.Serializable] public class Back { public bool Unlock { get; set; } public int FireRate { get; set; } public bool IsRotate { get; set; } public int RotateSpeed { get; set; } public int NumberOfBullets { get; set; } } [System.Serializable] public class Launchers { public Canon Canon { get; set; } public Rotator Rotator { get; set; } public Back Back { get; set; } } I have tried to use JObject, JArray and so on but can't find the proper way to be able to do something like that (which, in this case, doesn't work at all :( ).
void Start() { List<Launchers> jsonList = ReadJson(Application.dataPath + "/Resources/BDD/Launchers.json"); if(jsonList != null){ foreach (var item in jsonList) { if(item.Unlock){ // Do something } } } } static List<Launchers> ReadJson(string pathToJsonFile){ if(File.Exists(pathToJsonFile)){ JObject myjsonfile = JObject.Parse(File.ReadAllText(pathToJsonFile)); List<Launchers> launcherList = JsonConvert.DeserializeObject<List<Launchers>>(myjsonfile .ToString()); return launcherList; }else{ return null; } } Sorry for the long post but if someone have some hints/solution, it would be greattly appreciate
Launchersinstance or a single instance. But if you want to represent multiple launchers as a list, your JSON should use JSON array syntax:[ element1, element2 ]etcJsonConvert.DeserializeObject<Launchers>(...)instead ofJsonConvert.DeserializeObject<List<Launchers>>(...)Serializableattribute btw) calledLauncherwith those 5 properties, then deserialize to aDictionary<string, Launcher>. It depends on whether the namesCanon,RotatorandBackare really fixed or whether they're just the names that happen to be present. (We really don't have much context here.)