1儲存資料
1.1得到json格式的字元串
public string GetJson(string ip,int port)
{ //得到Json格式字元串
StringBuilder sb = new StringBuilder();
JsonWriter writer = new JsonWriter(sb);
writer.WriteObjectStart();
writer.WritePropertyName("ip"); //裡面有這些屬性
writer.Write(ip);
writer.WritePropertyName("port");
writer.Write(port);
writer.WriteObjectEnd(); //字典結束
return sb.ToString(); //傳回Json格式的字元串
}
這裡把要儲存的ip,port變量轉換成json格式的字元串
1.2儲存json格式的字元串到安卓機
public void SaveJsonString(string JsonString) //儲存Json格式字元串
{
string path = Application.persistentDataPath + "/JsonData.Json";
if (File.Exists(path) == true)
{
File.Delete(path);
}
FileInfo file = new FileInfo(path); //儲存檔案的路徑
StreamWriter writer = file.CreateText(); //用文本寫入的方式
writer.Write(JsonString); //寫入資料
writer.Close(); //關閉寫指針
writer.Dispose(); //銷毀寫指針
}
将上面的得到json字元串儲存到安卓機檔案存儲目錄
2讀取資料
public class IpPort
{
public string ip = "";
public int port = 0;
}
2.1json資料轉換成string
public string GetJsonString() //從檔案裡面讀取json資料
{ StreamReader reader = new StreamReader(Application.persistentDataPath + "/JsonData.Json");
string jsonData = reader.ReadToEnd();
reader.Close();
reader.Dispose();
return jsonData;
}
2.2JsonMapper.ToObject轉換
private IpPort m_ipPort = new IpPort();
string path = Application.persistentDataPath + "/JsonData.Json";
if (File.Exists(path) == true)
{
string data = GetJsonString();
m_ipPort = JsonMapper.ToObject<IpPort>(data);
}