I have been working on a save game solution for my project and have hit a wall. After several days of research, trial/ error etc. I decided to give the stack a shot. I am attempting to convert back from a Json text file into an object, then add it to a dictionary. It keeps giving my Invalid cast exceptions, regardless as to how I iterate through the Jdata object. Keeping in mind I am using LitJson 3rd party. Here is the code thus far. The error occurs at the foreach statement.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
using System.IO;
public static class SaveGame {
public static string savePath = Application.persistentDataPath +
"/Saves/";
public static int numberOfSaves = 0;
public static string saveFileName = PlayerCrew.playerShipName + ".json";
public static void SavePlayerData ()
{
string playerSavePath = savePath + saveFileName;
string jsonHolder;
jsonHolder = JsonMapper.ToJson(PlayerCrew.playerCrewManifest);
if (!File.Exists(playerSavePath))
{
FileStream fs = new FileStream(playerSavePath,
FileMode.OpenOrCreate);
fs.Close();
File.WriteAllText(playerSavePath, jsonHolder);
}
else
{
File.WriteAllText(playerSavePath, jsonHolder);
}
}
public static void LoadCrewManifest()
{
string playerSavePath = savePath + saveFileName;
string jsonHolder;
jsonHolder = File.ReadAllText(playerSavePath);
JsonData jdata = JsonMapper.ToObject(jsonHolder);
PlayerCrew.playerCrewManifest.Clear();
foreach (KeyValuePair<string,CrewMember> item in jdata)
{
PlayerCrew.playerCrewManifest.Add(item.Key, item.Value);
Debug.Log(item.Key);
}
}
}
The values in
jdata
might come asKeyValuePair<string, string>
the simplest way would be a simple constructor for your class
CrewMember
e.g. something likeThan you don't want the
item.key
since it will be the variable name (in this caseName
) instead you want theitem.Value
.Your json code could look like