首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试从JSONData对象反序列化时,Unity和LitJSON的c#遇到无效的强制转换异常

尝试从JSONData对象反序列化时,Unity和LitJSON的c#遇到无效的强制转换异常
EN

Stack Overflow用户
提问于 2018-11-12 08:07:27
回答 2查看 426关注 0票数 0

我一直在为我的项目开发一个保存游戏的解决方案,但是遇到了麻烦。经过几天的研究、试错等,我决定试一试这个堆栈。我正在尝试将Json文本文件转换回对象,然后将其添加到字典中。无论我如何遍历Jdata对象,它都会一直给出无效的强制转换异常。请记住,我使用的是第三方的LitJson。以下是到目前为止的代码。该错误发生在foreach语句中。

代码语言:javascript
复制
 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);
        }

    }





    }
EN

回答 2

Stack Overflow用户

发布于 2018-11-12 09:36:49

我建议您使用NetJson。您可以使用泛型类型反序列化,包括Dictionary。

票数 0
EN

Stack Overflow用户

发布于 2018-11-13 14:24:32

jdata中的值可能为KeyValuePair<string, string>

最简单的方法是为您的类CrewMember创建一个简单的构造函数,例如

代码语言:javascript
复制
[Serializable]
public class CrewMember
{
    public string Name;

    public CrewMember(string name)
    {
        Name = name;
    }
}

那么您不需要item.key,因为它将是变量名(在本例中为Name),而您需要的是item.Value

您的json代码可能如下所示

代码语言:javascript
复制
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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53254496

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档