Young87

SmartCat's Blog

So happy to code my life!

游戏开发交流QQ群号60398951

当前位置:首页 >跨站数据测试

C# 如何使用Json+字典(Dictionary)处理 键值对

首先,引入命名空间:

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>();
    }

运行结果:
在这里插入图片描述

除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog

上一篇: 使用LiteOS Studio图形化查看LiteOS在STM32上运行的奥秘

下一篇: 让垃圾分类开发“极快致简”的好物件,零基础的开发小白也能轻松驾驭它!

精华推荐