【问题标题】:Java Jackson JSON without POJOs没有 POJO 的 Java Jackson JSON
【发布时间】: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


    【解决方案1】:

    如果您不想创建自己的对象模型,那么 Jackson 有一个 JsonNode class

    如果您不想对数据做任何事情,您可以返回一个String 并将以下注释添加到您的方法中:

    @Produces(MediaType.APPLICATION_JSON) 
    

    【讨论】:

    • 谢谢,现在正在查看。我还需要更改帖子吗?我怎样才能得到字符串,它只是身体吗?
    • 是的。您也可以将帖子正文作为字符串接受
    • 所有关于 JsonNode 的网站都建议使用它来将 json 翻译成 POJO。所以,它没有看到一个很好的例子。
    猜你喜欢
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    相关资源
    最近更新 更多