Skip to content

Support more date-time formats for JSON deserialization #85545

Closed
@gregsdennis

Description

@gregsdennis

Description

Originally reported to JsonSchema.Net here.

The report says that System.Text.Json deserialization only supports ISO 8601 date-time formats. However JSON Schema specifies that RFC 3339 formats are to be used.

Thus a problem exists when a payload that has been validated by the schema:

{
  "type": "string",
  "format": "date-time"
}

(with format validation enabled) fails to deserialize because there is a mismatch between the format required by JSON Schema and the formats supported by System.Text.Json's deserialization.

This restriction is especially odd since DateTime.Parse() supports these formats.

Reproduction Steps

Please see attached solution.

[Test]
public void Test1()
{
	var serializerOptions = new JsonSerializerOptions
	{
		WriteIndented = true,
		Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
	};

	var jsonDate = JsonNode.Parse("\"2023-03-20 05:41:23.3881075\"");

	Console.WriteLine(jsonDate.AsJsonString());

	JsonSchema schema = new JsonSchemaBuilder()
		.Type(SchemaValueType.String)
		.Format(Formats.DateTime);

	var results = schema.Evaluate(jsonDate, new EvaluationOptions
	{
		OutputFormat = OutputFormat.List,
		RequireFormatValidation = true
	});

	Console.WriteLine(JsonSerializer.Serialize(results, serializerOptions));
	Assert.IsTrue(results.IsValid);

	var date = jsonDate.Deserialize<DateTime>(); // fails

	Console.WriteLine(date);
}

[Test]
public void DateTimeParsing()
{
	var date = DateTime.Parse("2023-03-20 05:41:23.3881075"); // works

	Console.WriteLine(date);
}

Expected behavior

Date/time deserialization is more tolerant and accepts any format that can be handled by DateTime.Parse().

Actual behavior

Date/time deserialization MUST be ISO 8601-1:2019.

Regression?

Unsure.

Known Workarounds

A custom converter should be able to handle this, but it shouldn't really be necessary.

Configuration

These tests run in .Net 6. JsonSchema.Net is .Net Standard 2.0.

Other information

Maybe serialization could be configurable.

Date-time format comparison: https://ijmacd.github.io/rfc3339-iso8601/

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions