首先,引入命名空间:
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>();
}
运行结果:
更多推荐
C# 如何使用Json+字典(Dictionary)处理 键值对
发布评论