Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
788 views
in Technique[技术] by (71.8m points)

json - Jackson: is there a way to serialize POJOs directly to 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?

The use-case is as follows:

  • Server-side templating is done with the Java implementation of Mustache. This uses Jackson's TreeModel.
  • After that, I need a slimmed-down version of the TreeModel on the client-side, so I want to be able to first filter the TreeModel, serialize that to JSON, then send it to the client-side for further processing.

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();

Anyone?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To answer my own question:

JsonNode node = objectMapper.valueToTree(map);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...