使用LitJson的JSON数组到C#数组

时间:2016-10-18 20:56:43

标签: c# arrays json unity5 litjson

我正在尝试将CS​​ON中的数组转换为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#脚本中阅读它?我试过定义&#34;属性&#34; (有了这条线

(type)buildingData [i] ["properties"]

)作为一个bool [],一个带有新公共类属性的List(我卡住了),绝望之外,还有一个ArrayList和一个BitArray。

但不要让我用这些方法做到这一点的失败阻止你,如果你相信你知道如何做到这一点那么我可能会做错了。我非常感谢你,如果非常感谢,你可以给予任何帮助!

0 个答案:

没有答案