对象和 JSON 之间来回转换
System.Text.Json 可以把对象序列化成 JSON,也可以把 JSON 反序列化回对象。
Student 对象
Name
小王
Age
18
Courses
C#, JSON
CamelCase 选项把 Name/Age/Courses 写成 name/age/courses。
对应代码
var student = new Student("小王", 18, ["C#", "JSON"]);
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
string json = JsonSerializer.Serialize(student, options);
Student? roundTrip =
JsonSerializer.Deserialize<Student>(json, options);
public sealed record Student(
string Name,
int Age,
List<string> Courses);
public sealed record AuditRecord(
[property: JsonPropertyName("id")] int Id,
string Message,
[property: JsonIgnore] string Secret);