引入命名空间:using Newtonsoft.Json;
(需下载Newtonsoft.Json.dll,下载地址 https://github.com/JamesNK/Newtonsoft.Json/releases
,网盘地址:链接:https://pan.baidu.com/s/1XLXtUH0ks5jPsgoex_8VnA 提取码:b665 )
解压
将解压文件夹中的C:\Users\Administrator\Desktop\Json120r2\Bin\net20\Newtonsoft.Json.dll 放到unity 目录下
代码:
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;
}
}