序列化和反序列化对象集合

时间:2019-10-29 09:53:09

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

我正在尝试创建一个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;
    }
}

2 个答案:

答案 0 :(得分:0)

我仍在学习c#,但可能是您将序列化为一系列播客,而序列化时则是序列化为对象类型。

答案 1 :(得分:0)

这里似乎有几个问题:

  1. 您正在检查是否存在与您正在读取/写入的文件不同的文件。前一个文件名中有多余的空格。避免此问题的最佳方法是使用变量包含文件名,而不是在三个单独的位置对其进行硬编码。
  2. 您对正在编写和阅读的JSON格式不一致:
    • 首次创建文件时(在第一个分支中),您正在编写一个包含属性Podcast的JSON对象,该属性随后包含一个播客。
    • 当您尝试读取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
}
相关问题