c# - 使用 System.Text.Json 将 JSON 反序列化为对象
问题描述
我正在尝试使用System.Text.Json.Serialization
命名空间将 JSON 文件中的文本反序列化为名为 Note 的对象,然后访问其属性。后来打算读入多个 Note 对象,然后存储在一个列表中。
除了在 DOTNET 文档https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-中,似乎没有很多关于使用此命名空间的示例至
这是我根据给出的示例进行的尝试。这会引发如下所示的错误,如果您知道我做错了什么,请告诉我,谢谢。
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 和其他选项,但我宁愿使用这个(如果可能的话)
解决方案
你的Note
类需要一个无参数的构造函数
class Note
{
public DateTime currentDate { get; set; }
public string summary { get; set; }
// add this
public Note()
{
}
public Note(DateTime _date, string _sum)
{
currentDate = _date;
summary = _sum;
}
}
如果您需要原始的两个参数构造函数,可能值得考虑。如果你删除了它,那么你可以Note
像这样实例化一个新的
var completeNote = new Note
{
currentdate = date,
summary = givenNote
};
推荐阅读
- google-chrome - 将 Chrome OS 键盘快捷键与普通的 3rd 方键盘一起使用?概览模式?
- shell - 有什么方法可以自动制作 shell 脚本别名?
- react-native - 访问 redux 持久化外部组件
- search - 为什么 Shift+F3 在 Notepad++ 中停止工作?
- python - Discord BOT with Python,如何让它在我们发送命令的频道中回复(完成)
- c# - Blazor 字段为空
- linux - 从 s3 存储桶下载多个大于某个时间戳的文件
- python - Python Tkinter - 如何在画布中包含小部件?
- python - 使用两个列表排序产生的排序对第三个列表进行排序?
- node.js - 在 Angular 应用程序中使用前进和后退导航箭头时断开套接字