Unity使用LitJson加载json文本
首先导入LitJson到Plugins文件夹下 创建json文本如下 进行加载文本
json对象对应类型
[ System. Serializable ]
public class Item {
public string mName;
public int mWidth;
public int mHeight;
public int mNeedLv;
public int mNeedGreen;
public int mAddArea;
public int mNeedGlod;
public string mNeedTimer;
public int mAddGold;
public int mAddExp;
}
public class LoadJsonManager : MonoBehaviour
{
private readonly string mPath= "crops" ;
private List< Item> mItemList;
private void Start ( ) {
mItemList= new List< Item> ( ) ;
TextAsset textAsset= Resources. Load < TextAsset> ( mPath) ;
JsonData data= JsonMapper. ToObject ( textAsset. text) ;
foreach ( JsonData temp in data)
{
string name= GetJsonValue ( temp, "name" ) ;
int width= int . Parse ( GetJsonValue ( temp, "width" ) ) ;
int height= int . Parse ( GetJsonValue ( temp, "height" ) ) ;
int needLv= int . Parse ( GetJsonValue ( temp, "needLv" ) ) ;
int needGreen= int . Parse ( GetJsonValue ( temp, "needGreen" ) ) ;
int addArea= int . Parse ( GetJsonValue ( temp, "AddArea" ) ) ;
int needGold= int . Parse ( GetJsonValue ( temp, "needGold" ) ) ;
string needTime= GetJsonValue ( temp, "needTime" ) ;
int addGold= int . Parse ( GetJsonValue ( temp, "AddGold" ) ) ;
int addExp= int . Parse ( GetJsonValue ( temp, "AddExp" ) ) ;
mItemList. Add ( new Item ( ) { mName= name, mWidth= width, mHeight= height, mNeedLv= needLv, mNeedGreen= needGreen, mAddArea= addArea,
mNeedGlod= needGold, mNeedTimer= needTime, mAddGold= addGold, mAddExp= addArea} ) ;
}
}
public string GetJsonValue ( JsonData temp, string str)
{
return temp[ str] . ToString ( ) ;
}
}