[英]c# With Unity and LitJSON Getting an Invalid Cast Exception when trying to de-serialize back from JSONData object
我一直在為我的項目開發一個保存游戲解決方案,並且碰壁了。 經過幾天的研究,嘗試/錯誤等,我決定嘗試一下。 我正在嘗試從Json文本文件轉換回一個對象,然后將其添加到字典中。 不管我如何遍歷Jdata對象,它始終為我提供Invalid cast異常。 請記住,我正在使用LitJson 3rd party。 這是到目前為止的代碼。 錯誤發生在foreach語句中。
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);
}
}
}
我建議您使用NetJson 。 您可以使用通用類型(包括字典)進行反序列化。
jdata
的值可能為KeyValuePair<string, string>
最簡單的方法是為您的類CrewMember
一個簡單的構造函數,例如
[Serializable]
public class CrewMember
{
public string Name;
public CrewMember(string name)
{
Name = name;
}
}
比起您不需要item.key
因為它是變量名(在本例中為Name
),而不是item.Value
。
您的json代碼可能看起來像
JsonData jdata = JsonMapper.ToObject(jsonHolder);
PlayerCrew.playerCrewManifest.Clear();
foreach (KeyValuePair<string,string> item in jdata)
{
PlayerCrew.playerCrewManifest.Add(item.Value, new CrewMember(item.Value));
Debug.Log(item.Value);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.