How to Convert Dictionary value to List<MyClass> in Unity

3.8k views Asked by At

I saved my class using JsonFx libraries, into "Saved.json" file, and I want to parse json file for loading my saved class data

But I can't find way to change Dictionary to my class type. Would you tell me how can it works? I tried to like this..

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

Here is my code.

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

There are 2 answers

2
AudioBubble On

Not familiar with the jsonfx and whether it's possible to let it directly read to a list (that would probably be the preferred way), but it's very easy to get the Values of a Dictionary in a List:

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
0
Meneleus On

I realize this is old but for completeness:

.ToList() works fine, but, it should be noted that it requires:

using System.Linq;