[英]When deserializing JSON I'm getting `System.InvalidCastException`
So, basically, I have this simple JSON serializer/deserializer application in C# where I save StringCollections into .txt
files that have JSON inside them.所以,基本上,我在 C# 中有这个简单的 JSON 序列化器/反序列化器应用程序,我将 StringCollections 保存到其中包含 JSON 的.txt
文件中。 So, basically, I can successfully save my JSON to a raw text file like this:所以,基本上,我可以成功地将我的 JSON 保存到这样的原始文本文件中:
String path = Properties.Settings.Default.database + "//data.txt";
StringCollection data = Properties.Settings.Default.data;
File.WriteAllText(path, JsonSerializer.Serialize(data));
But when desirializing the file to get the object using this code:但是当反序列化文件以使用以下代码获取对象时:
string rawJson = File.ReadAllText(path);
StringCollection data = JsonSerializer.Deserialize<StringCollection>(rawJson);
It gives me this exception:它给了我这个例外:
System.InvalidCastException : 'Unable to cast object of type 'System.Text.Json.JsonElement' to type 'System.String'.' System.InvalidCastException :“无法将“System.Text.Json.JsonElement”类型的对象转换为“System.String”类型。”
I searched for this one StackOverflow and found a couple of posts about it, but they really didn't solve my problem.我搜索了这个 StackOverflow 并找到了几篇关于它的帖子,但它们确实没有解决我的问题。 What am I doing wrong?我究竟做错了什么?
NOTE: I'm using System.Text.Json
and not Newtonsoft.Json
.注意:我使用的是System.Text.Json
而不是Newtonsoft.Json
。
As Per Microsoft documentation the below is the supported types https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to :根据 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
So StringCollection
is in System.Collections.Specialized
namespace.所以StringCollection
在System.Collections.Specialized
命名空间中。 So its not supported, you have 2 choices所以它不支持,你有 2 个选择
List<string>
将您的返回类型更改为例如: List<string>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.