【发布时间】:2014-10-24 12:32:19
【问题描述】:
我正在尝试使用 JAX-RS (Jersey) 创建一个简单的 REST 服务,而不使用 Spring。我在我的实体中使用 Joda 作为日期字段。
为了配置自动 json 映射,我创建了一个 JsonMapperProvider,我在其中添加了 JodaModule:
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JsonMapperProvider implements ContextResolver<ObjectMapper> {
final ObjectMapper objectMapper;
public JsonMapperProvider() {
objectMapper = new ObjectMapper();
objectMapper.registerModule(new JodaModule());
}
@Override
public ObjectMapper getContext(Class<?> arg0) {
return objectMapper;
}
}
这是我的资源类:
@Path("users")
public class UserController {
@Inject
private UserService userService;
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public User getUserById(@PathParam("id") Long id) {
return userService.findById(id);
}
}
我正在使用“no web.xml”配置,这个类:
@ApplicationPath("api")
public class RestApplication extends ResourceConfig {
}
但它不起作用...... User 实体中的 LocalDate 字段始终返回为空。
我发现的唯一解决方法是在 ResourceConfig 类中注册所有组件(包括来自 jersey-media-json-jackson 的 JacksonFeature 类),如下所示:
@ApplicationPath("api")
public class RestApplication extends ResourceConfig {
public RestApplication() {
super(
UserController.class,
JsonMapperProvider.class,
JacksonFeature.class
);
}
}
这个问题还有其他解决方案吗?我不想在这个类中手动注册我所有的服务和其他东西......
【问题讨论】:
标签: java json jackson jax-rs jodatime