[英]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.