swagger-api / swagger-api/swagger-codegen

[JAVA] dateLibrary "java8-localdatetime" option is broken

Open
#6,992 12 comments 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Client: Java General: Suggestion
Dominant language
Mustache
Stars
17.8k
Forks
6k
PR merge metrics
No merged PRs in 30d

Description

Description

Using dateLibrary option with java8-localdatetime value generates JSON.java with Gson type adapter for parsing LocalDate not LocalDateTime (as expected).

As a result, this option is useless for parsing date-time fields (the common scenario).

Swagger-codegen version

2.2.3

Command line used for generation

Options:

  • language: java
  • dateLibrary: java8-localdatetime
Suggestion for a fix

Add also LocalDateTime adapter. Both types should be supported (as they are supported by Swagger/OpenAPI). And LocalDateTime is the more useful type.

Workaround

In user code, create the correct type adapter:

  class LocalDateTimeTypeAdapter extends TypeAdapter<LocalDateTime> {

    private final DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

    @Override
    public void write(JsonWriter out, LocalDateTime date) throws IOException {
      if (date == null) {
        out.nullValue();
      } else {
        out.value(formatter.format(date));
      }
    }

    @Override
    public LocalDateTime read(JsonReader in) throws IOException {
      switch (in.peek()) {
        case NULL:
          in.nextNull();
          return null;
        default:
          String date = in.nextString();
          return LocalDateTime.parse(date, formatter);
      }
    }
  }

And register it with Gson:

    apiClient.getJSON().setGson(
      new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new LocalDateTimeTypeAdapter()).create());

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the generator template or entry point that produces JSON.java for the java8-localdatetime option. Reproduce generation with language java and dateLibrary java8-localdatetime, then inspect whether adapters cover both LocalDate and LocalDateTime. Done means date-time fields parse correctly while LocalDate support remains available.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.