Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 823
Geert-Jan Avatar asked Aug 06 '11 14:08

Geert-Jan


People also ask

Which library is used for serializing POJOs?

The Jackson library provides annotations that you can use in POJOs to control both serialization and deserialization between POJOs and JSON.

Does Jackson use serializable?

Note that Jackson does not use java. io. Serializable for anything: there is no real value for adding that. It gets ignored.

How do you serialize an object to JSON Jackson in Java?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.

How do I read JSON file with ObjectMapper?

Read Object From JSON via URL ObjectMapper objectMapper = new ObjectMapper(); URL url = new URL("file:data/car. json"); Car car = objectMapper. readValue(url, Car. class);


1 Answers

To answer my own question:

JsonNode node = objectMapper.valueToTree(map); 
like image 108
Geert-Jan Avatar answered Sep 22 '22 04:09

Geert-Jan