问题描述
我正在编写一个典型的Play Framework应用程序,我希望使用Jackson从Controller的方法返回一个JsonNode。
这就是我在做的方式现在:
public static结果foo(){
MyPojoType myPojo = new myPojo();
String tmp = new ObjectMapper()。writerWithView(JSONViews.Public.class).writeValueAsString(myPojo);
JsonNode jsonNode = Json.parse(tmp);
返回ok(jsonNode);
}
是否可以避免String tmp复制并直接从MyPojoType转换使用视图到JsonNode?
也许我可以使用ObjectMapper.valueToTree,但我不知道如何为它指定JSonView。
经过更多调查,这就是我最后所做的,以避免多余的工作:
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(){returnapplication / json; }
};
} catch(JsonProcessingException exc){
Logger.error(toResult:,exc);
}
if(ret == null)
return Results.badRequest();
返回Results.ok(ret);
}
总结:方法ok,badRequest等接受play.mvc。内容类。然后,只需使用它来包装序列化的json对象。
I'm writing a typical Play Framework app where I want to return a JsonNode from my Controller's methods, using Jackson.
This is how I'm doing it right now:
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);
}
Is it possible to avoid the "String tmp" copy and convert directly from MyPojoType to JsonNode using a view?
Maybe I can use ObjectMapper.valueToTree, but I don't know how to specify a JSonView to it.
After more investigation, this is what I did in the end to avoid the redundant work:
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);
}
In summary: The methods ok, badRequest, etc accept a play.mvc.Content class. Then, simply use it to wrap your serialized json object.
这篇关于使用JsonView将POJO转换为JsonNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!