Unity 通过 LitJson 读取 Json 枚举数据

Json 文件:

    {
        "_Type": "Material",
        "_Quality": "Epic",
        "_ID": 4,
        "_Count": 2,
        "_BuyPrice": 3000,
        "_SellPrice": 1500,
        "_Name": "蓝宝石",
        "_Description": "这个是史诗级的合成材料!",
        "_Sprite": "gem"
    }

Item 实体类:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class Item
{
    /// 
    /// 物品类型
    /// 
    public enum _Item_Type
    {
        Consumable,
        Equipment,
        Weapon,
        Material
    }
    /// 
    /// 物品品质
    /// 
    public enum _Item_Quality
    {
        Poor,
        Common,
        Uncommon,
        Rare,
        Epic,
        Legendary,
        Heirloom
    }
    
    private _Item_Type _type;
    private _Item_Quality _quality;
    private int _id;
    private int _count;
    private int _buyPrice;
    private int _sellPrice;
    private string _name;
    private string _description;
    private string _sprite;


    //通过 json 获取到的 string 值给本实体类的枚举赋值
    public string _Type
    {
        set
        {
            _type = (_Item_Type)System.Enum.Parse(typeof(_Item_Type), value);
        }
    }
    public string _Quality
    {
        set
        {
            _quality = (_Item_Quality)System.Enum.Parse(typeof(_Item_Quality), value);
        }
    }
    public int _ID
    {
        get { return _id; }
        set { _id = value; }
    }
    public int _Count
    {
        get { return _count; }
        set { _count = value; }
    }
    public int _BuyPrice
    {
        get { return _buyPrice; }
        set { _buyPrice = value; }
    }
    public int _SellPrice
    {
        get { return _sellPrice; }
        set { _sellPrice = value; }
    }
    public string _Name
    {
        get { return _name; }
        set { _name = value; }
    }
    public string _Description
    {
        get { return _description; }
        set { _description = value; }
    }
    public string _Sprite
    {
        get { return _sprite; }
        set { _sprite = value; }
    }

    public override string ToString()
    {
        return string.Format("物品类型:{0},物品品质:{1},ID:{2},数量:{3},购买价格:{4},卖出价格:{5},名称:{6},描述:{7},图片:{8}"
            , _type, _quality, _id, _count, _buyPrice, _sellPrice, _name, _description, _sprite);
    }
}

_Type 和 _Quality 是两个枚举类型。

属性为只写属性,因为LitJson自动识别public string 属性比较方便,通过识别到的 value转换为本 Item实体类的枚举值。

 //通过 json 获取到的 string 值给本实体类的枚举赋值
    public string _Type
    {
        set
        {
            _type = (_Item_Type)System.Enum.Parse(typeof(_Item_Type), value);
        }
    }

本类的私有值赋值成功,OK了。

 private _Item_Type _type;

你可能感兴趣的:(学习)