Back to journal
json MAR 18 · 2014

Examples for working with JSON in Play Framework 2 with Java

  • 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>

Follow Brian Porter on LinkedIn →
← Previous Next →
Brian Porter

Written by

poornerd

CTO at an automotive data company in Munich. Co-founder of SiteForce AG. Four decades writing software and shipping production systems.

Keep reading

Related essays