I am trying to convert an array in JSON to a sort of array (Maybe a list?) in C# for a Unity game. I have tried everything I can think of to do this, but with no success. Here is an example of the JSON that I am trying to convert, without an array:
[
{
"id": 0,
"name": "Name 0",
"description": "Description for id 0 goes here."
},
{
"id": 1,
"name": "Name 1",
"description": "Description for id 1 goes here."
}
]
And here is how I go about converting it to a list in C#:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LitJson;
using System.IO;
public class BuildingSystem : MonoBehaviour {
private List<BuildObjects> database = new List<BuildObjects>();
private JsonData buildingData;
void Start() {
buildingData = JsonMapper.ToObject(File.ReadAllText(Application.dataPath + "/StreamingAssets/Buildings.json"));
ConstructBuildingDatabase();
}
void ConstructBuildingDatabase() {
for (int i = 0; i < buildingData.Count; i++) {
database.Add (new BuildObjects ((int)buildingData [i] ["id"],
(string)buildingData [i] ["name"],
(string)buildingData [i] ["description"]));
}
}
}
public class BuildObjects {
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public BuildObjects (int id, string name, string description) {
this.ID = id;
this.Name = name;
this.Description = description;
public BuildObjects() {
this.ID = -1;
}
}
If I wanted to add a new variable to the JSON like this for example:
[
{
"id": 0,
"name": "Name 0",
"description": "Description for id 0 goes here.",
"properties": [{"bool": true, "string": "text goes here"},{"bool": false, "string": "more text goes here"}]
}
]
How could I read it in my C# script? I have tried defining "properties" (With this line
(type)buildingData [i] ["properties"]
) as a bool[], a List with a new public class Properties (on which I got stuck), and out of desperation, an ArrayList and a BitArray.
But don't let my failure to do it with these methods deter you, if you believe you know how to do it as one of these then I probably tried it wrong. I'm quite stuck on this, any help you can give if greatly appreciated!