使用JsonView将POJO转换为JsonNode

我正在编写一个典型的Play Framework应用程序,我希望使用Jackson从Controller的方法返回JsonNode。

这就是我现在正在做的事情:

public static Result foo() { MyPojoType myPojo = new myPojo(); String tmp = new ObjectMapper().writerWithView(JSONViews.Public.class).writeValueAsString(myPojo); JsonNode jsonNode = Json.parse(tmp); return ok(jsonNode); } 

是否可以避免“String tmp”副本并使用视图直接从MyPojoType转换为JsonNode?

也许我可以使用ObjectMapper.valueToTree,但我不知道如何为它指定一个JSonView。

有趣的问题: valueToTree ,我不认为有一个特定的方法,你的代码是最直接的方式: valueToTree方法不适用任何视图。 因此代码很好。

经过更多的调查,这是我最终做的,以避免多余的工作:

 public Result toResult() { Content ret = null; try { final String jsonpayload = new ObjectMapper().writerWithView(JsonViews.Public.class).writeValueAsString(payload); ret = new Content() { @Override public String body() { return jsonpayload; } @Override public String contentType() { return "application/json"; } }; } catch (JsonProcessingException exc) { Logger.error("toResult: ", exc); } if (ret == null) return Results.badRequest(); return Results.ok(ret); } 

总结:方法ok,badRequest等接受play.mvc.Content类。 然后,只需使用它来包装序列化的json对象。

据我所知,使用jax-rs,你可以这样做:

 public Response toResult() throws JsonProcessingException { final ObjectWriter writer = new ObjectMapper() .writerWithView(JSONViews.Public.class); return Response.ok(new StreamingOutput() { @Override public void write(OutputStream outputStream) throws IOException, WebApplicationException { writer.writeValue(outputStream, /*Pojo*/ payload); } }).build(); } 

所以你必须在Play框架中找到一个能够流式传输结果的类(通过OutputStream

我认为这是更有效的方式

 public Result toResult() { MyPojo result = new MyPojo(); JsonNode node = objectMapper.valueToTree(result); return ok(node); }