引入命名空間:using Newtonsoft.Json;
(需下載Newtonsoft.Json.dll,下載地址 https://github.com/JamesNK/Newtonsoft.Json/releases
,網(wǎng)盤地址:鏈接: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>
/// 字典轉(zhuǎn)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轉(zhuǎn)字典
/// </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;
}
}