Customize JSON serialization with JaxRS

后端 未结 1 832
清酒与你
清酒与你 2021-02-05 18:45

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

{
  \"date\" : \"30/06/2014\",
  \"price\" : {
    \"val\" : \"12.50\",
    \"c         


        
相关标签:
1条回答
  • 2021-02-05 19:01

    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.

    0 讨论(0)
提交回复
热议问题