0

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> ..?

    }
}
이현욱
  • 21
  • 1
  • 4

2 Answers2

2

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
  • thanks! then how can I use the value in the list? I want to change type of object list... – 이현욱 Dec 08 '18 at 11:50
  • Sorry I completely misunderstoond your question. Sadly I don't know anything but if I understood correctly what you want now your question might be similar to this one: https://stackoverflow.com/questions/21092870/deserialize-a-dictionary-with-jsonfx –  Dec 08 '18 at 12:28
1

I realize this is old but for completeness:

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

using System.Linq;
Meneleus
  • 21
  • 3