【发布时间】:2016-02-18 05:52:05
【问题描述】:
我目前正在将一个节点项目转换为 DW。节点项目当前将来自客户端的 JSON 存储为字符串,然后在客户端获取相同资源时返回 application/JSON。这基本上是一个键/值存储重置端点。
我想用 dropwizard 实现相同的功能,但我不想绘制出整个结构,它是 POJO 中的嵌套结构。有没有办法允许这样做?我只想将 JSON 保存为带有密钥的数据库中的字符串,我根本不想在 java 应用程序中处理数据。
既然 API 要求我返回一个对象,那么该对象应该是什么?这是我为 DW 提供的函数,您可以看到它期望返回一个对象。
@GET
@UnitOfWork
@Timed
@ApiOperation(value="Find value by ID", notes="Get a value object from the DAO using ID as the sole criterion")
@ApiResponses(value={
@ApiResponse(code=400, message="Invalid ID"),
@ApiResponse(code=404, message="No object found by specified ID")
})
public SomeJavaOjbectMustGoHere getSample(
@ApiParam(value="id of object to get", required=true)
@QueryParam("id")
Long id
) throws WebApplicationException {
SomeJavaOjbectMustGoHere returned = dao.get(id);
if (returned == null) throw new WebApplicationException(Response.Status.NOT_FOUND);
else return returned;
}
这是来自节点的大部分代码:
module.exports = function (server) {
function createResponse(req, res, next) {
var key = req.params.name;
console.log("Creating Response for key: '" + req.params.name + "'");
// ...some validation...
if (..blah..) {
// fail out.
res.send(403, "response can not be saved without a valid key and structure.");
return next();
}
var data = JSON.stringify(req.body);
// ... store the stuff in the db...
res.send(201, "Saved");
return next();
}
function getResponse(req, res, next) {
try {
var payload = {};
// ... get the data matching the key...
res.header("Content-Type", "application/json");
res.send(200, JSON.parse(payload.toString()));
}
catch(err) {
console.log('Data not found.' + err);
res.send(200,
{
"id": Math.random().toString(36).substr(3, 8),
// ... default structure ...
});
}
return next();
}
function send(req, res, next) {
res.send('response ' + req.params.name);
return next();
}
server.post('/response/:name', createResponse);
server.put('/response', send);
server.get('/response/:name', getResponse);
server.head('/response/:name', send);
server.del('/response/:name', function rm(req, res, next) {
res.send(204);
return next();
});
}
【问题讨论】:
标签: java json jackson dropwizard