我正在尝试将 JSON 中的数组转换为 C# 中的一种数组(可能是列表?)以用于 Unity 游戏。我已经尝试了我能想到的一切来做到这一点,但没有成功。这是我尝试转换的 JSON 示例,没有数组:
[
{
"id": 0,
"name": "Name 0",
"description": "Description for id 0 goes here."
},
{
"id": 1,
"name": "Name 1",
"description": "Description for id 1 goes here."
}
]
以下是我如何将其转换为 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;
}
}
如果我想像这样向 JSON 添加一个新变量,例如:
[
{
"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"}]
}
]
我怎么能在我的 C# 脚本中阅读它?我试过定义“属性”(用这一行
(type)buildingData [i] ["properties"]
) 作为 bool[],一个带有新公共类 Properties 的 List(我被困在上面),出于绝望,一个 ArrayList 和一个 BitArray。
但是不要让我未能使用这些方法阻止你,如果你相信你知道如何做这些方法之一,那么我可能尝试错了。我非常坚持这一点,如果非常感谢您可以提供任何帮助!