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

编程入门 行业动态 更新时间:2024-10-25 22:26:11

首先,引入命名空间:

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)处理 键值对

本文发布于:2023-06-14 09:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1462604.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   键值   字典   Json   Dictionary

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!