【问题标题】:Serializing and deserializing a collection of objects序列化和反序列化对象集合
【发布时间】:2020-02-24 13:09:56
【问题描述】:

我正在尝试创建一个 Rssfeed 阅读器,它将有关播客的信息保存到 JSON 文件中,但我在序列化和反序列化到该文件时遇到了问题。

我意识到关于这个主题还有其他线索,但我无法掌握或理解如何将其应用于我的代码或它背后的推理。

所以我有一些代码可以在文件不存在时创建一个文件,并将 JSON 数据写入其中,如下所示:

public void SaveFile(Podcast podcast)
{
    try
    {
        JsonSerializer serializer = new JsonSerializer();

        if(!File.Exists(@"C: \Users\Kasper\Desktop\Projektuppgift\Projektuppgift - Delkurs2\Projektet\Projektet\bin\Debug\podcasts.json"))
        {
            string json = JsonConvert.SerializeObject( new { Podcast = podcast });
            StreamWriter sw = File.CreateText(@"C:\Users\Kasper\Desktop\Projektuppgift\Projektuppgift-Delkurs2\Projektet\Projektet\bin\Debug\podcasts.json");
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                serializer.Serialize(writer, json);
            }
        }
        else
        {
            var filepath = @"C:\Users\Kasper\Desktop\Projektuppgift\Projektuppgift-Delkurs2\Projektet\Projektet\bin\Debug\podcasts.json";
            var jsonData = File.ReadAllText(filepath);
            var podcasts = JsonConvert.DeserializeObject<List<Podcast>>(jsonData) ?? new List<Podcast>();
            podcasts.Add(podcast);
            jsonData = JsonConvert.SerializeObject(new {PodcastList = podcasts });
            File.WriteAllText(filepath, jsonData);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("IO Exception ", ex.Message);
    }
}

我无法从这个文件中反序列化并向其中添加一个对象。有没有更简单的方法可以向 JSON 文件添加更多数据,还是我遗漏了什么?

Podcast 类如下所示:

public class Podcast
{
    public string url { get; set; }

    public string name { get; set; }

    public int updateInterval { get; set; }

    public string category { get; set; }
    //public Category category = new Category();

    public List<Episode> episodes { get; set; }

    public Podcast(string url, string name, Category category, List<Episode> episodes, int updateInterval)
    {
        this.url = url;
        this.name = name;
        this.category = category.name;
        this.episodes = episodes;
        this.updateInterval = updateInterval;
    }

    public Podcast(Podcast p)
    {
        this.url = p.url;
        this.name = p.name;
        this.category = p.category;
        this.episodes = p.episodes;
        this.updateInterval = p.updateInterval;
    }
}

【问题讨论】:

  • new { Podcast = podcast }) -- 你可能想在那里创建一个新的List&lt;Podcast&gt;,而不是一个具有单个Podcast 属性的新匿名对象。

标签: c# json serialization json.net json-deserialization


【解决方案1】:

我还在学习 c#,但可能是您反序列化为播客列表,而当您序列化时,您将序列化为对象类型。

【讨论】:

  • 你将如何序列化到播客列表?或者你会用另一种方式序列化它吗?
  • tbh 我不知道我使用 json 序列化的时间我通常使用他们的属性/标记我的数据,因此它有助于映射,尝试检查 json 中的属性
【解决方案2】:

这里似乎有几个问题:

  1. 您正在检查是否存在与您正在读取/写入的文件不同的文件。前一个文件名中有多余的空格。避免此问题的最佳方法是使用变量来包含文件名,而不是将其硬编码在三个不同的位置。
  2. 你写和读的 JSON 格式不一致:
    • 当您第一次创建文件时(在第一个分支中),您正在编写一个 JSON 对象,其中包含一个属性 Podcast,该属性随后包含一个播客。
    • 当您尝试读取 JSON 文件时,会将整个 JSON 视为播客列表。
    • 将新播客添加到列表后,您将 JSON 编写为包含 PodcastList 属性的单个对象,该属性随后包含列表。

您需要使用一致的 JSON 格式。我建议您将代码分解成更小的方法来读取和写入 podcasts.json 文件,这样更容易推理:

public static List<Podcast> ReadPodcastsFromFile(string filepath)
{
    if (!File.Exists(filepath)) return new List<Podcast>();

    string json = File.ReadAllText(filepath);
    return JsonConvert.DeserializeObject<List<Podcast>>(json);
}

public static void WritePodcastsToFile(List<Podcast> podcasts, string filepath)
{
    string json = JsonConvert.SerializeObject(podcasts);
    // This will overwrite the file if it exists, or create a new one if it doesn't
    File.WriteAllText(filepath, json);
}

然后,您可以将您的 SaveFile 方法简化为这样(我很想将其重命名为 SavePodcast):

public void SaveFile(Podcast podcast)
{
    var filepath = @"C:\Users\Kasper\Desktop\Projektuppgift\Projektuppgift-Delkurs2\Projektet\Projektet\bin\Debug\podcasts.json";
    List<Podcast> podcasts = ReadPodcastsFromFile(filepath);
    podcasts.Add(podcast);
    WritePodcastsToFile(podcasts, filepath);
}

请注意,我还从SaveFile 中删除了异常处理。您应该将其移至调用 SaveFile 的任何位置,以便在抛出异常时可以在该点采取适当的措施,例如:

try
{
    SaveFile(podcast);
}
catch (Exception ex)
{
    // Show a message to the user indicating that the file did not save
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 2014-12-24
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多