轉(zhuǎn)載請注明鏈接,謝謝:)
核心代碼:
0.使用LitJson.dll
在Unity項(xiàng)目中載入LitJson.dll 下載
using LitJson;
1.制作一個(gè)類遣疯,用于儲存和解析數(shù)據(jù)
public class UserData {
public string id;
public string loginId;
public int userID;
public double time; //不能使用float
}
2.保存數(shù)據(jù)
a.首先用LitJson把UserData轉(zhuǎn)化為string
b.用StreamWrite寫入本地
c.其中如果要用在iOS和Android設(shè)備,存儲路徑最好是用Application.persistentDataPath
private string tempPath = Application.persistentDataPath + "/temp.json";
public void SaveTempData()
{
FileInfo fileInfo = new FileInfo(tempPath);
//把類轉(zhuǎn)換為Json格式的String
string str = JsonMapper.ToJson(tempData);
//寫入本地
StreamWriter sw = fileInfo.CreateText();
sw.WriteLine(str);
sw.Close();
sw.Dispose();
}
3.解析Json為類
a.把一段json格式的字符串轉(zhuǎn)換為類
public void LoadTempData(String tempString)
{
FileInfo fileInfo = new FileInfo(tempPath);
if (fileInfo.Exists){
string tempString = File.ReadAllText(tempPath);
tempData = JsonMapper.ToObject<TempData>(tempString);
}
}
4.解析Json為通用格式
a.使用JsonData作為數(shù)據(jù)通用格式
b.JsonData和HashTable很類似,讀出的數(shù)據(jù)需要進(jìn)行類型轉(zhuǎn)換
JsonData js = JsonMapper.ToObject(www.text);
tempData.loginId = (string)js["id"];