Skip to content

OpenApiJsonWriter: Invalid DateTime serialization #291

@n-batrakov

Description

@n-batrakov

Expected Behavior

When using OpenApiJsonWriter valid JSON-string is written to TextWriter.

Actual Behavior

Writing OpenApiDocument with DateTime values (e.g example in parameters) results in invalid JSON-string with DateTime values not enclosed in quotes.

Example:

Code:

private static string ConvertToJson(string yaml)
{
    var reader = new OpenApiStringReader();
    var oas = reader.Read(yaml, out _);

    var stringWriter = new StringWriter();
    var openApiWriter = new MyOpenApiJsonWriter(stringWriter);
    oas.SerializeAsV3(openApiWriter);

    return stringWriter.ToString();
}

Input:

openapi: 3.0.0
info:
  version: 0.0.0
  title: Test
paths:
  /:
    get:
      parameters:
        - in: query
          name: q
          schema:
            type: string
          example: '1970-01-01T00:00:00Z'
      responses:
        '200':
          description: _

Output:

{
  "openapi": "3.0.1",
  "info": {
    "title": "Test",
    "version": "0.0.0"
  },
  "paths": {
    "/": {
      "get": {
        "parameters": [
          {
            "name": "q",
            "in": "query",
            "schema": {
              "type": "string"
            },
            "example": 1970-01-01T00:00:00.0000000+00:00
          }
        ],
        "responses": {
          "200": {
            "description": "_"
          }
        }
      }
    }
  }
}

Note example property.

See failing test case

Additional Information

I suspect the reason for this behavior is OpenApiWriterBase which writes DateTimeOffset values directly to TextWriter insted of WriteValue(string).

As a workaround for now I use

class MyOpenApiJsonWriter : OpenApiJsonWriter
{
    public MyOpenApiJsonWriter(TextWriter textWriter): base(textWriter)
    {
    }

    public override void WriteValue(DateTimeOffset value) 
    {
        WriteValue(value.ToString("o"));
    }
}

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions