【发布时间】:2020-05-03 13:21:31
【问题描述】:
我正在尝试使用 System.Text.Json.Serialization 命名空间将 JSON 文件中的文本反序列化为名为 Note 的对象,然后访问其属性。后面的意图是读入多个 Note 对象,然后存储在一个 List 中。
除了在 DOTNET 文档https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to 中之外,似乎没有太多关于此命名空间使用的示例
这是我根据给出的示例进行的尝试。这会引发如下所示的错误,如果您知道我做错了什么,请告诉我,谢谢。
class Note
{
public DateTime currentDate { get; set; }
public string summary { get; set; }
public Note(DateTime _date, string _sum)
{
currentDate = _date;
summary = _sum;
}
}
class Program
{
static void Main(string[] args)
{
//Write json data
string path = @"D:\Documents\Projects\Visual Projects\Notes Data\ThingsDone.json";
DateTime date = DateTime.Now;
string givenNote = "summary text";
Note completeNote = new Note(date, givenNote);
string serialString = JsonSerializer.Serialize(completeNote);
File.WriteAllText(path, serialString);
//Read json data
string jsonString = File.ReadAllText(path);
Note results = JsonSerializer.Deserialize<Note>(jsonString);
Console.WriteLine(results.summary);
}
}
我还研究了 Json.NET 和其他选项,但我宁愿使用这个(如果可能的话)
【问题讨论】:
-
system.text.json 不支持使用参数化构造函数反序列化对象,请参阅Exception parsing json with System.Text.Json.Serialization。您将需要添加一个无参数构造函数。除此之外,我们还需要查看您尝试反序列化的 JSON——即 minimal reproducible example.
-
可能你需要提供无参数的构造函数,甚至是你的 Note 类的私有函数
标签: c# json json-deserialization system.text.json