C# 如何使用Json+字典(Dictionary)處理 鍵值對
阿新 • • 發佈:2020-12-12
首先,引入名稱空間:
using LitJson;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
下面展示 Json+字典(Dictionary)序列化和反序列化處理 鍵值對
。
public void JsonTest() {
//以LitJson方式儲存鍵值對
JsonData jd = new JsonData();
jd["BattleStep"] = "1" ;
jd["sss"] = "2";
jd["aaa"] = "3";
//將物件序列化為字串
string jsonDate = JsonMapper.ToJson(jd);
Debug.Log(jsonDate);
//以字典形式把json資料反序列化為物件,反序列化後存入字典
Dictionary<string, string> tempDic = JsonMapper.ToObject< Dictionary<string, string>>(jsonDate);
//修改指定key對應的Value
string val;
if (tempDic.TryGetValue("BattleStep", out val))
{
//如果指定的字典的鍵存在,value +1
tempDic["BattleStep"] = (int.Parse(val)+1).ToString();
}
else
{
//不存在,則新增
tempDic.Add("BattleStep", "0");
}
//修改後重新將字典序列化為字串
jsonDate = JsonMapper.ToJson(tempDic);
Debug.Log(jsonDate);
//---------------------字典其他常用方法
//遍歷字典
foreach (KeyValuePair<string, string> kvp in tempDic)
{
if (kvp.Value.Equals("2"))
{
Debug.Log(kvp.Key);
}
}
foreach (string key in tempDic.Keys)
{
if (key.Equals("BattleStep"))
{
Debug.Log(key);
}
}
//判斷字典中是否有指定Key或Value
//if(tempDic.ContainsKey("BattleStep"))
//if(tempDic.ContainsValue("1"))
//獲取字典中第一個Key == "BattleStep"的Value
Debug.Log(tempDic.FirstOrDefault(q => q.Key == "BattleStep").Value);
//linq 獲取所有Key
var keys = tempDic.Where(q => q.Value == "1").Select(q => q.Key);
//獲取所有Key
List<string> keyList = (from q in tempDic
where q.Value == "2"
select q.Key).ToList<string>();
}
執行結果: