Unity Json---LitJson插件的使用


1、LitJson下載

百度雲
鏈接:https://pan.baidu.com/s/1BmmqLJ5asX2DSDxfR29KLQ
提取碼:80gl

2、LitJson如何使用

Json文本內容 Items

[
    {
        "id": 1,
        "name": "血瓶",
        "type": "Consumable",
		"sprite": "Sprites/Items/hp"
    },
    {
        "id": 2,
        "name": "長劍",
        "type": "Weapon",
		"sprite": "Sprites/Items/Saber"
    }
]

對應Json的物品類

public class Item
{
    /// <summary>
    /// 物品ID
    /// </summary>
    public int ID { get; set; }

    /// <summary>
    /// 物品名字
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// 物品類型
    /// </summary>
    public ItemType Type { get; set; }

	/// <summary>
    /// 物品資源地址
    /// </summary>
    public string Sprite { get; set; }

    public Item(int id , string name,ItemType type,string sprite)
    {
        this.ID = id;
        this.Name = name;
        this.Type = type;
        this.Sprite = sprite;
    }

    /// <summary>
    /// 物品類型
    /// </summary>
    public enum ItemType
    {
        Consumable, //消耗品
        Weapon   //裝備
    }
}

解析Json類 Items

public class JsonTest : MonoBehaviour
{
    private List<Item> database = new List<Item>();

    void Start()
    {
        ParseItemJson();
    }

    /// <summary>
    /// 解析物品信息
    /// </summary>
    private void ParseItemJson()
    {
        //獲取Json中的文本。文本在unity中是textasset類型
        TextAsset itemText = Resources.Load<TextAsset>("Items");
        //把json文本轉換為jsondata格式
        JsonData itemData = JsonMapper.ToObject(itemText.text);

        //對每一個物品,都新建個item類來存儲
        for (int i = 0; i < itemData.Count; i++)
        {
            int id = (int)itemData[i]["id"];
            string name = (string)itemData[i]["name"];

            //枚舉類型則要把字符串轉換為枚舉類型
            //用System.Enum.Parse方法
            Item.ItemType type = (Item.ItemType)System.Enum.Parse(typeof(Item.ItemType), itemData[i]["type"].ToString());
            string sprite = (string)itemData[i]["Sprite"];

            Item item = new Item(id, name, type,sprite);
            database.Add(item);
        }
        Debug.Log(itemList[1]);
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM