Skip to content

OpenApiJsonWriter: Invalid DateTime serialization #291

Closed

Description

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"));
    }
}

Activity

  1. darrelmiller commented on Jul 16, 2018

    @darrelmiller
    Member

    Nikita Batrakov (@n-batrakov) Thanks for the detailed write-up on this. I will get a fix out for this before the next release.

  2. self-assigned this
    on Sep 27, 2018
  3. PerthCharern commented on Sep 27, 2018

    @PerthCharern
    Contributor

    Update: I have the fix now, and will get it out for PR when I'm done with tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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