0

我一直在为我的项目开发保存游戏解决方案,但遇到了困难。经过几天的研究、试验/错误等,我决定试一试堆栈。我正在尝试将 Json 文本文件转换回对象,然后将其添加到字典中。无论我如何遍历 Jdata 对象,它都会不断地给出我的无效强制转换异常。请记住,我正在使用 LitJson 3rd 方。这是到目前为止的代码。错误发生在 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);
        }

    }





    }
4

2 回答 2

0

中的值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);
}
于 2018-11-13T06:24:32.240 回答
0

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

于 2018-11-12T01:36:48.737 回答