In a webservice call, I would like to return my objects with this JSON structure.
{
\"date\" : \"30/06/2014\",
\"price\" : {
\"val\" : \"12.50\",
\"c
If you are using Jackson (which should be the default for JBoss EAP 6) you can use custom JsonSerializers
For the 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 the 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 Serializers 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;
}
}
For parsing JSON in this custom format you need to implement custom JsonDeserializers.
If you are using Jettison you can do the same thing with custom XmlAdapters.