Skip to content

Code in vs4win/Chapter09/WorkingWithJson (Chapter 9) doesn’t match the book’s output #132

@wxici

Description

@wxici

Image
"Figure 1"
Image
"Figure 2"

At most, it only produces the following Book.json file and console output?

Image "Figure 3"

This is from C# 10 and .NET 6 – Introduction to Cross-Platform Development (6th Edition), Tsinghua University Press, translated by Ye Weiming. Does this count as an oversight or an error?"

"Moreover, the Book class contains a public DateOnly PublishDate; field. Although .NET 6 introduced the DateOnly type, System.Text.Json does not provide built-in serialization support for it. Built-in support for DateOnly is only available starting from .NET 7. In .NET 6, a custom converter must be added manually."

public class DateOnlyJsonConverter : JsonConverter
{
private const string Format = "'year:'yyyy,'month:'MM,'day:'dd,";
public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> DateOnly.ParseExact(reader.GetString()!, Format, null);

public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
    => writer.WriteStringValue(value.ToString(Format));

}

options.Converters.Add(new DateOnlyJsonConverter()); // Register the converter

Only in this way can the output shown in Figure 3 be achieved.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions