使用 System.Text.Json 将 JSON 反序列化为对象
Deserialize JSON into an Object(s) using System.Text.Json
我正在尝试使用 System.Text.Json.Serialization
命名空间将 JSON 文件中的文本反序列化为名为 Note 的对象,然后访问其属性。稍后打算读入多个 Note 对象,然后存储在一个列表中。
除了 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 和其他选项,但我宁愿使用这个(如果可能的话)
您的 Note
class 需要一个无参数构造函数
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
};
我正在尝试使用 System.Text.Json.Serialization
命名空间将 JSON 文件中的文本反序列化为名为 Note 的对象,然后访问其属性。稍后打算读入多个 Note 对象,然后存储在一个列表中。
除了 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 和其他选项,但我宁愿使用这个(如果可能的话)
您的 Note
class 需要一个无参数构造函数
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
};