C# 反序列化JSON I';我得到'System.InvalidCastException'`

C# 反序列化JSON I';我得到'System.InvalidCastException'`,c#,json,winforms,C#,Json,Winforms,因此,基本上,我在C中有一个简单的JSON序列化程序/反序列化程序应用程序,我将StringCollections保存到.txt文件中,其中包含JSON。因此,基本上,我可以成功地将JSON保存到原始文本文件中,如下所示: String path = Properties.Settings.Default.database + "//data.txt"; StringCollection data = Properties.Settings.Default.data; File.WriteAl

因此,基本上,我在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);
string rawJson=File.ReadAllText(路径);
StringCollection data=JsonSerializer.Deserialize(rawJson);
这给了我一个例外:

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

我搜索了这个StackOverflow,找到了一些关于它的帖子,但它们并没有解决我的问题。我做错了什么


注意:我使用的是
System.Text.Json
,而不是
Newtonsoft.Json

,根据Microsoft文档,以下是支持的类型:

映射到JavaScript原语的
.NET原语,如数字类型、字符串和布尔值。
用户定义的普通旧CLR对象(POCO)。
一维和交错阵列(ArrayName[][])。
TValue为object、JsonElement或POCO的字典。
来自以下名称空间的集合。
系统.集合
System.Collections.Generic
System.Collections.Immutable
所以
StringCollection
位于
System.Collections.Specialized
命名空间中。所以它不受支持,您有两个选择

  • 实现自定义转换器:
  • 将您的退货类型更改为for ex:
    List

  • 如何使变量名数据与string和StringCollection相同。。请包括真正的代码片段,以便我们可以support@HanyHabib我将更改变量名以消除混淆。这些代码片段位于不同的函数上。您能显示序列化JSON文件的示例吗?也可能是
    System.Text.Json
    不支持
    StringCollection
    反序列化。@很抱歉,Json文件是保密的,但我从Hany那里得到了答案。谢谢大家!哦,对了!我不知道,因为我一直在使用Newtonsoft.Json库。谢谢
    .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