Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

Most of the marshalling I have to do it done by Spring. However, I sometimes have to do this manually. Let’s see how easy it is with Jackson 2 (FasterXML).

Maven dependency

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.3</version>
</dependency>

Import the ObjectMapper

The ObjectMapper is the object that you will instantiate and use for all conversions.

import com.fasterxml.jackson.databind.ObjectMapper;

Object to String

Given an object, it is pretty easy to use an ObjectMapper.

ObjectMapper objectMapper = new ObjectMapper();
String myString = objectMapper.writeValueAsString(myObject);

String to Object

If you have a JSON string and need to convert that to an object, you also use the ObjectMapper.

ObjectMapper objectMapper = new ObjectMapper();
MyObject myObject = objectMapper.readValue(myJsonString, MyObject.class);

May 12th, 2016

Posted In: FasterXML, Java, java ninja, Javaninja, json

Leave a Reply

Your email address will not be published. Required fields are marked *

WP to LinkedIn Auto Publish Powered By : XYZScripts.com