如何在Unity中将字典值转换为List <myclass>

时间:2018-12-08 07:29:09

标签: c# unity3d jsonfx

我使用JsonFx库将类保存到“ Saved.json”文件中, 而且我想解析json文件以加载保存的课程数据

但是我找不到将Dictionary更改为我的类类型的方法。您能告诉我它如何运作吗? 我试图喜欢这个。.

List<object> readStageList = new List<object>();
readStageList = (List<object>)readJson["data"];

这是我的代码。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using JsonFx.Json;
using System.IO;
using System;
using System.Linq;


public class Data : MonoBehaviour {
    public class Json
    {
        public static string Write(Dictionary<string, object> dic){
            return JsonWriter.Serialize(dic);
        }
        public static Dictionary<string, object> Read(string json){
            return JsonReader.Deserialize<Dictionary<string, object>>(json);
        }
    }
    public class StageData
    {
        public int highscore;
        public StageData(int highscore)
        {
            this.highscore = highscore;
        }
    }

    void Start () {
        Dictionary<string, object> dicJson = new Dictionary<string, object>();
        StageData stageOne = new StageData(10);
        StageData stageTwo = new StageData(20);
        List<StageData> stageList = new List<StageData>();
        stageList.Add(stageOne);
        stageList.Add(stageTwo);
        dicJson.Add("data",stageList);

        string strJson = Json.Write(dicJson);
        string path = pathForDocumentsFile("Saved.json");
        File.WriteAllText(path, strJson);

        Dictionary<string, object> readJsonDic = new Dictionary<string, object>();
// how can I change this readJsonDic to List<StageData> ..?

    }
}

2 个答案:

答案 0 :(得分:1)

不熟悉jsonfx以及是否可以直接将其读取到列表(这可能是首选方式),但是很容易在列表中获取字典的值:

Dictionary<string, object> dict = new Dictionary<string, object>()
{
    ["firstKey"] = "some string as value",
    ["secondKey"] = 42
};
List<object> objects = dict.Values.ToList(); //will contain the string "some string as value" and the int 42

答案 1 :(得分:0)

我意识到这是旧的,但为了完整性:

.ToList() 工作正常,但需要注意的是:

using System.Linq;