使用JaxRS自定义JSON序列化 [英] Customize JSON serialization with JaxRS

查看:288
本文介绍了使用JaxRS自定义JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在webservice调用中,我想使用此JSON结构返回我的对象​​。

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

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

我想将此JSON代码映射到此Java结构(使用 joda-time joda-money ):

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

public class MyResponse {
  LocalDate date;
  Money price;
}

我的网络服务目前看起来像这样:

My webservice currently looks like this:

@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 do I register a custom handler to format dates as I want as well as money representations?

推荐答案

如果您使用 Jackson (这应该是JBoss EAP 6的默认设置)你可以使用自定义 JsonSerializers

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

对于 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"));
    }

}

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;
    }

}

用于解析此自定义格式的JSON您需要实现自定义 JsonDeserializers

For parsing JSON in this custom format you need to implement custom JsonDeserializers.

如果您正在使用 Jettison ,您可以使用自定义 XmlAdapters

If you are using Jettison you can do the same thing with custom XmlAdapters.

这篇关于使用JaxRS自定义JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆