50

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?

malana
  • 5,045
  • 3
  • 28
  • 41
Geert-Jan
  • 18,623
  • 16
  • 75
  • 137

1 Answers1

82

To answer my own question:

JsonNode node = objectMapper.valueToTree(map);
2240
  • 1,547
  • 2
  • 12
  • 30
Geert-Jan
  • 18,623
  • 16
  • 75
  • 137
  • 4
    Indeed. And in general, 'ObjectMapper.convertValue(sourceOb, dstType)' can be used for various conversions, including POJO to tree case. – StaxMan Aug 07 '11 at 06:18
  • 2
    It appears that ObjectMapper.valueToTree wasn't added until version 1.6, so the 'ObjectMapper.convertValue(sourceObj, JsonNode.class)' alternative from @StaxMan is great for those of us that haven't upgraded yet! – Steve Onorato Nov 07 '14 at 00:15
  • It looks like `valueToTree` just adds the POJO as a `POJONode`, without serializing it into "basic" nodes, so it's not possible to deconstruct, filter, or alter the fields or descendants of the POJO. I'd love to have a simple solution for this... – dirkt Jun 15 '18 at 08:18
  • 2
    @dirkt use ObjectNode instead of JsonNode: ```mapper.valueToTree(map)``` – leonidv Feb 09 '20 at 06:27