【发布时间】:2017-04-22 22:05:05
【问题描述】:
我打算像这样将 JSON 数据发送到我的 JAX-RS 端点:
POST /myendpoint
{
"field1": "something",
"field2": "something else",
"field3": 12345
}
然后,当我检索一个对象时,我希望它包含在一个通用包装器中:
GET /myendpoint
{
"type": "MyEndpoint"
"items": [
{
"item": {
"id": 1,
"field1": "something",
"field2": "something else",
"field3": 12345
},
"link": "https://api.site.com/myendpoint/1"
},
{
"item": {
"id": 2,
"field1": "different",
"field2": "different else",
"field3": 67890
},
"link": "https://api.site.com/myendpoint/2"
}
],
"page_size": 10,
"page": 1,
"total": 2,
"message": ""
}
和
GET /myendpoint/2
{
"type": "MyEndpoint"
"items": [
{
"item": {
"id": 2,
"field1": "different",
"field2": "different else",
"field3": 67890
},
"link": "https://api.site.com/myendpoint/2"
}
],
"page_size": 10,
"page": 1,
"total": 1,
"message": ""
}
我开始在 Jersey 中使用 Jackson FasterXML 进行自动序列化/反序列化,即:
@Provider
public class JsonObjectMapperProvider implements ContextResolver<ObjectMapper> {
private final ObjectMapper objectMapper;
public JsonObjectMapperProvider() {
objectMapper = new ObjectMapper();
}
@Override
public ObjectMapper getContext(final Class<?> type) {
return objectMapper;
}
}
然后在资源中:
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void createMyEndpoint(MyEndpoint myEndpoint) {
myEndpointDao.create(myEndpoint);
// ...
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<MyEndpoint> createMyEndpoint() {
// I'm not actually sure how to do this one yet!! but I include it for completeness
return myEndpointDao.getAll();
}
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public MyEndpoint createMyEndpoint(@PathParam("{id}") id) {
return myEndpointDao.read(id);
}
这适用于未包含在包装器中的 MyEndpoint 对象,但我将如何包含包装器?还是有更好的方法来做到这一点?
JSON 的架构并不是一成不变的,如果还有什么更有意义的,那我就听好了。
【问题讨论】:
-
哪个版本的 jax-rs,2.0?
-
是的 JAX-RS 2.0,我使用的是 Jersey 2.25.1
标签: java json jersey jackson jax-rs