[英]How to Convert Dictionary value to List<MyClass> in Unity
我使用 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> ..?
}
}
不熟悉 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
我意识到这是旧的,但为了完整性:
.ToList()
工作正常,但需要注意的是,它需要:
using System.Linq;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.