此处为 Jersey 1.18.1。我在我的服务器上定义了以下 Jersey 资源:
@Path("/location")
@Produces(MediaType.APPLICATION_JSON)
public class LocationResourceImpl implements LocationResource {
private ObjectMapper mapper;
public LocationResourceImpl() {
super();
mapper = new ObjectMapper();
// TODO: Configure for JSON POJO mapping how?!?
}
@GET
@Path("address/{address_id}")
@Override
public Address getAddress(@PathParam("address_id") Long id) {
Address address;
address = new Address(
1L,
"19 ABC Dr",
"Suite 3",
"Testville",
"NY",
"US",
"12345");
return address;
}
}
我的地址
POJO 已使用@JsonProperty
注释进行了正确注释。我试图弄清楚如何配置我的 ObjectMapper
实例,以便 getAddress(Long)
返回的 Address
实例以 JSON 形式返回我的地址。
关于我能做什么有什么想法吗?看起来像 Jersey 2.x 中添加了 setSerializationConfig 和 setDeserializationConfig 方法,但升级对我来说不是一个选择,因为我使用的是 DropWizard 0.7.1,取决于 Jersey 1.18.x。
最佳答案
使用 Dropwizard,我们不需要任何特殊配置即可获得基本的 Jackson POJO 映射支持。正如 Dropwizard User Guide: How it's Glued Together 中所述:
When your application starts up, it will spin up a Jetty HTTP server, see
DefaultServerFactory
. This server will have two handlers, one for your application port and the other for your admin port.The application port has an
HttpServlet
as well, this is composed ofDropwizardResourceConfig
, which is an extension of Jersey’s resource configuration that performs scanning to find root resource and provider classes.
DropwizardResourceConfig
is where the variousResourceMethodDispatchAdapter
are registered to enable the following functionality:
- Enables using Jackson to parse request entities into objects and generate response entities from objects, all while performing validation.
关于java - 配置 Jersey 1.18.x 服务器以进行 JSON POJO 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27370685/