C# Json字符串和Dictionary字典相互转换

2019-08-08  本文已影响0人  带着面包去流浪

引入命名空间:using Newtonsoft.Json;

(需下载Newtonsoft.Json.dll,下载地址 https://github.com/JamesNK/Newtonsoft.Json/releases
,网盘地址:链接:https://pan.baidu.com/s/1XLXtUH0ks5jPsgoex_8VnA 提取码:b665 )

1.png

解压

将解压文件夹中的C:\Users\Administrator\Desktop\Json120r2\Bin\net20\Newtonsoft.Json.dll 放到unity 目录下


2.png

代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
public class JsonAndDictionary : MonoBehaviour {
    /// <summary>
    /// 字典转json字符串
    /// </summary>
    /// <param name="myDic"></param>
    /// <returns></returns>
    public static string DictionaryToJson(Dictionary<string,string> myDic) {
        string jsonStr= JsonConvert.SerializeObject(myDic);
        return jsonStr;
    }

    /// <summary>
    /// json转字典
    /// </summary>
    /// <param name="jsonStr"></param>
    /// <returns></returns>
    public static Dictionary<string,string> JsonToDictionary(string jsonStr) {
        Dictionary<string,string> dic= JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonStr);
        return dic;
    }
}
上一篇下一篇

猜你喜欢

热点阅读