0

我使用 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> ..?

    }
}
4

2 回答 2

2

不熟悉 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
于 2018-12-08T09:43:38.417 回答
1

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

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

using System.Linq;
于 2021-03-21T01:30:07.553 回答