【问题标题】:How to Convert Dictionary value to List<MyClass> in Unity如何在 Unity 中将字典值转换为 List<MyClass>
【发布时间】:2018-12-08 07:29:08
【问题描述】:

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

    }
}

【问题讨论】:

  • 你为什么要反序列化到List&lt;object&gt;而不是List&lt;MyClass&gt;
  • 你可以试试:var myList = (List&lt;StageData&gt;)readJsonDic["data"];
  • 参见 Linq:List&lt;TypaA&gt; example.ToList&lt;TypeB&gt;(); 仅在值可以隐式转换时才有效

标签: c# unity3d jsonfx


【解决方案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

【讨论】:

  • 谢谢!那么我该如何使用列表中的值呢?我想更改对象列表的类型...
  • 对不起,我完全误解了你的问题。可悲的是,我什么都不知道,但如果我正确理解了您现在想要的内容,您的问题可能与此类似:stackoverflow.com/questions/21092870/…
【解决方案2】:

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

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

using System.Linq;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    • 2022-06-29
    相关资源
    最近更新 更多