Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JsonbConfig for JAX-RS #75

Closed
jsonbrobot opened this issue Apr 9, 2018 · 3 comments
Closed

JsonbConfig for JAX-RS #75

jsonbrobot opened this issue Apr 9, 2018 · 3 comments
Labels
question Further information is requested

Comments

@jsonbrobot
Copy link

I'm developing Java EE 8 app using JAX-RS.
I have LocalDateTime fields in my Entities.
When I return those entities from JAX-RS resource methods, I indicate desired formatting with @JsonbDateFormat annotation.
Is it possible to define my formatting somewhere once, so it's applied to all entities?

@jsonbrobot
Copy link
Author

@kret11
Copy link

kret11 commented Nov 23, 2018

Create LocalDateTime adapter and use it in your own ContextResolver

@kret11
Copy link

kret11 commented Nov 23, 2018

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

@Provider
public class JsonbConfig implements ContextResolver<Jsonb> {

  private static Jsonb instance;

  public static Jsonb getInstance() {
    if (instance == null) {
      javax.json.bind.JsonbConfig config = new javax.json.bind.JsonbConfig()
          .withDateFormat("yyyy-MM-dd'T'HH:mmXXX", null).withAdapters(new LocalTimeCustomAdapter());
      instance = JsonbBuilder.create(config);
    }
    return instance;
  }

  @Override
  public Jsonb getContext(Class<?> type) {
    return getInstance();
  }

}
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import javax.json.bind.adapter.JsonbAdapter;

public class LocalTimeCustomAdapter implements JsonbAdapter<LocalTime, String> {

  private final static DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm");

  @Override
  public String adaptToJson(LocalTime obj) throws Exception {
    return TIME_FORMATTER.format(obj);
  }

  @Override
  public LocalTime adaptFromJson(String obj) throws Exception {
    return LocalTime.parse(obj, TIME_FORMATTER);
  }

}

@aguibert aguibert added the question Further information is requested label Dec 17, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants