Examples for working with JSON in Play Framework 2 with Java

Posted by Brian Porter on March 18, 2014
  • String to JSON:  <pre class="brush: plain; title: ; notranslate" title="">JsonNode json = mapper.readTree(notification.getSharedData());</pre>

  • Json to Object:  <pre class="brush: plain; title: ; notranslate" title="">Asset asset = mapper.readValue(a.toString(), Asset.class)</pre>

  • Json to extisting Object:  <pre class="brush: plain; title: ; notranslate" title="">asset = mapper.readerForUpdating(asset).readValue(assetJson.toString())</pre>

  • Object to JsonString: <pre class="brush: plain; title: ; notranslate" title="">mapper.writeValueAsString(new ResultDocument(document))</pre>

  • Convert Object ot JsonNode: <pre class="brush: plain; title: ; notranslate" title="">JsonNode documentNode = mapper.convertValue(document, JsonNode.class);</pre>

    This causes an error – Caused by: com.fasterxml.jackson.databind.JsonMappingException: Direct self-reference leading to cycle so do this workaround:

    String messageJson = null;
    
    

String documentAsString = BaseApiController.mapper.writeValueAsString(document);

JsonNode documentNode = BaseApiController.mapper.readTree(documentAsString);</pre>

If you made it this far, you may as well follow me on LinkedIn: Follow Brian Porter