Jackson:有没有办法将 POJO 直接序列化为树模型? [英] Jackson: is there a way to serialize POJOs directly to treemodel?

查看:13
本文介绍了Jackson:有没有办法将 POJO 直接序列化为树模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法将一些 POJO 直接转换为 Jackson TreeModel.我知道存在从 POJO 到 JSON-String 的翻译,并且支持 TreeModel 到 JSON-String - 但是我正在寻找 POJO 到 TreeModel 的翻译.有办法吗?

I'm looking for a way to directly convert some POJO to a Jackson TreeModel. I know that a translation from POJO-to-JSON-String exists, and TreeModel-to-JSON-String is supported — hovewer I am looking for a POJO-to-TreeModel translation. Is there a way?

用例如下:

  • 服务器端模板是通过 Mustache 的 Java 实现完成的.这使用了 Jackson 的 TreeModel.
  • 之后,我需要在客户端使用精简版的 TreeModel,因此我希望能够首先过滤 TreeModel,将其序列化为 JSON,然后将其发送到客户端进行进一步处理.

理想情况下,这涉及两个序列化步骤.但是,在我的解决方法中,我目前使用了三个 — 您可以在此处看到:

This, ideally, involves two serialization steps. However, in my workaround, I am currently using three — which you can see here:

map = // a map of  pojos with jackson annotations

//pojo >> JSON
StringWriter w = new StringWriter();    
objectmapper.writeValue(new JsonFactory().createJsonGenerator(w), map);
String json = w.toString();
w.close();

//JSON >> Treemodel
JsonNode tree = GenericJcrDTO.mapper.readTree(json);
//filter tree here

//treemodel >>JSON
StringWriter w = new StringWriter();
GenericJcrDTO.mapper.writeValue(new JsonFactory().createJsonGenerator(w), tree);
json = w.toString();
w.close();

有人吗?

推荐答案

回答我自己的问题:

JsonNode node = objectMapper.valueToTree(map);

这篇关于Jackson:有没有办法将 POJO 直接序列化为树模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆