Unity要将Json解析成字典,首先得引用Newtonsoft.Json.dll文件,然后得自己定义一个反序列化Json的类。
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using System;
- using Newtonsoft.Json;
- using System.IO;
- public class Test : MonoBehaviour
- {
- void Start()
- {
- StreamReader streamReader = new FileInfo(Application.streamingAssetsPath + "/Product.json").OpenText();
- Product.dic = DeserializeStringToDictionary<string, Fruit>(streamReader.ReadToEnd());
- }
- public class Product
- {
- public static Dictionary<string, Fruit> dic = new Dictionary<string, Fruit>();
- }
- public class Fruit
- {
- public string apple;
- public string pear;
- }
- public static Dictionary<TKey, TValue> DeserializeStringToDictionary<TKey, TValue>(string jsonStr)
- {
- if (string.IsNullOrEmpty(jsonStr))
- return new Dictionary<TKey, TValue>();
- Dictionary<TKey, TValue> jsonDict = JsonConvert.DeserializeObject<Dictionary<TKey, TValue>>(jsonStr);
- return jsonDict;
- }
- }