首页 > 解决方案 > 反序列化 JSON 时,我得到了 `System.InvalidCastException`

问题描述

所以,基本上,我在 C# 中有一个简单的 JSON 序列化器/反序列化器应用程序,我将 StringCollections 保存到.txt其中包含 JSON 的文件中。所以,基本上,我可以成功地将我的 JSON 保存到一个原始文本文件中,如下所示:

String path = Properties.Settings.Default.database + "//data.txt";
StringCollection data = Properties.Settings.Default.data;

File.WriteAllText(path, JsonSerializer.Serialize(data));

但是在反序列化文件以使用此代码获取对象时:

string rawJson = File.ReadAllText(path);
StringCollection data = JsonSerializer.Deserialize<StringCollection>(rawJson);

它给了我这个例外:

System.InvalidCastException:'无法将'System.Text.Json.JsonElement'类型的对象转换为'System.String'类型。

我搜索了这个 StackOverflow 并找到了几篇关于它的帖子,但它们确实没有解决我的问题。我究竟做错了什么?

注意:我正在使用System.Text.Json而不是Newtonsoft.Json.

标签: c#jsonwinforms

解决方案


根据 Microsoft 文档,以下是支持的类型https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to

.NET primitives that map to JavaScript primitives, such as numeric types, strings, and Boolean.
User-defined Plain Old CLR Objects (POCOs).
One-dimensional and jagged arrays (ArrayName[][]).
Dictionary<string,TValue> where TValue is object, JsonElement, or a POCO.
Collections from the following namespaces.
System.Collections
System.Collections.Generic
System.Collections.Immutable

StringCollection在命名空间中也是如此System.Collections.Specialized。所以它不支持,你有2个选择

  1. 实施自定义转换器:https ://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to
  2. 将您的退货类型更改为例如:List<string>

推荐阅读