c# - 反序列化 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
.
解决方案
根据 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个选择
- 实施自定义转换器:https ://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to
- 将您的退货类型更改为例如:
List<string>
推荐阅读
- java - Spring Boot AWS S3 文件读取错误 - 无法验证数据下载的完整性
- python - 如何根据另一列中的值填充组中的 np.nan 列?
- android - Flutter 错误,手势捕获的异常,处理手势时引发以下 _CastError:Null check operator used on a null value
- python - 预计有多个列表值,但只得到 1
- sql - 在 SQL Developer 查询中每滚动 12 小时标记 2 个实际读数与基准读数
- linux - macOS 中的 cp 命令无法识别“-t”标志
- npm - GitHub Actions Upload Artifact 未从 npm run build 中找到提供的路径
- azure-devops - 如何将 Azure SQL 数据库从一个备份到另一个?
- reactjs - 在 Safari 移动版中,当焦点更改时,表单会意外重置
- laravel - Laravel 来自模型或控制器的多维独特记录,无需 foreach