Customize JSON serialization using JaxRS

In a webservice call, I would like to return my objects using this JSON structure.

{ "date" : "30/06/2014", "price" : { "val" : "12.50", "curr" : "EUR" } } 

I would like to map this JSON code to this Java structure ( joda-time and joda-money ):

 public class MyResponse { LocalDate date; Money price; } 

Now my web service is as follows:

 @javax.ws.rs.POST @javax.ws.rs.Path("test") @javax.ws.rs.Produces({MediaType.APPLICATION_JSON}) @javax.ws.rs.Consumes({MediaType.APPLICATION_JSON}) public MyResponse test(MyRequest request) { MyResponse response = new MyResponse(); response.setDate(LocalDate.now()); response.setMoney(Money.parse("EUR 12.50")); return response; } 

So my question is: where can I register a custom handler for formatting dates, as I want, and for monetary representations?

+8
java json jax-rs
source share
1 answer

If you are using Jackson (which should be the default for JBoss EAP 6), you can use custom JsonSerializers

For LocalDate :

 public class DateSerializer extends JsonSerializer<LocalDate> { @Override public void serialize(LocalDate date, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeString(date.toString("dd/MM/yyyy")); } } 

For Money :

 public class MoneySerializer extends JsonSerializer<Money> { @Override public void serialize(Money money, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("val", money.getAmount().toString()); jgen.writeStringField("curr", money.getCurrencyUnit().getCurrencyCode()); jgen.writeEndObject(); } } 

Both Serializer can be registered globally:

 @Provider public class JacksonConfig implements ContextResolver<ObjectMapper> { private ObjectMapper objectMapper; public JacksonConfig() { objectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("MyModule", new Version(1, 0, 0, null)); module.addSerializer(Money.class, new MoneySerializer()); module.addSerializer(LocalDate.class, new DateSerializer()); objectMapper.registerModule(module); } public ObjectMapper getContext(Class<?> objectType) { return objectMapper; } } 

To parse JSON in this custom format, you need to implement custom JsonDeserializers .

If you use Jettison , you can do the same with custom XmlAdapters .

+8
source share

All Articles