JavaEE 8 - JsonB global JSONConfigurator

JSON-B from Java EE 8 allows to set the PropertyNamingStrategy.
Pass your custom configuration to the JsonbBuilder and return the instance with a ContextResolver:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.json.bind.JsonbConfig;
import javax.json.bind.config.PropertyNamingStrategy;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

@Provider
public class JSONConfigurator implements ContextResolver<Jsonb> {
@Override
public Jsonb getContext(Class<?> type) {
JsonbConfig config = getJsonbConfig();
return JsonbBuilder.newBuilder().withConfig(config).build();
}

private JsonbConfig getJsonbConfig() {
return new JsonbConfig().withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES);
}
}

In Wildfly 14 you have to add the JSONConfigurator in the Application.

To use it also in the Jax-RS Client just register the JSONConfigurator in the ClientBuilder.

1
2
3
4
5
6
7
8
9
private static WebTarget createClient() {
Logger logger = Logger.getLogger(CLASS);
Feature feature = new LoggingFeature(logger, Level.INFO, null, null);

return ClientBuilder.newBuilder()
.register(feature)
.register(new JSONConfigurator())
.build().target("http://localhost:8080/api/v1");
}

Jpa Convert from JPA allows to write a custom db converter.
We can store a list of integers in a comma seperated way and use therefore an characterfield:

1
2
3
4
5
6
7
8
9
10
11
12
@Converter
public class IntegerListConverter implements AttributeConverter<List<Integer>, String> {
@Override
public String convertToDatabaseColumn(List<Integer> attribute) {
return attribute.stream().map(Object::toString).collect(Collectors.joining(","));
}

@Override
public List<Integer> convertToEntityAttribute(String dbData) {
return Arrays.asList(dbData.split("\\s*,\\s*")).stream().map(Integer::valueOf).collect(Collectors.toList());
}
}

How to use:

1
2
3
@Convert(converter = IntegerListConverter.class)
@Column(name = "what_ever")
private List<Integer> whatEver = Collections.emptyList();