Java Language Using Jackson Object Mapper


Pojo Model

public class Model {
    private String firstName;
    private String lastName;
    private int age;
    /* Getters and setters not shown for brevity */        

Example: String to Object

Model outputObject = objectMapper.readValue(
//result: John

Example: Object to String

String jsonString = objectMapper.writeValueAsString(inputObject));
//result: {"firstName":"John","lastName":"Doe","age":23}


Import statement needed:

import com.fasterxml.jackson.databind.ObjectMapper;

Maven dependency: jackson-databind

ObjectMapper instance

//creating one
ObjectMapper objectMapper = new ObjectMapper();
  • ObjectMapper is threadsafe
  • recommended: have a shared, static instance


<T> T readValue(String content, Class<T> valueType)  
  • valueType needs to be specified -- the return will be of this type
  • Throws
    • IOException - in case of a low-level I/O problem
    • JsonParseException - if underlying input contains invalid content
    • JsonMappingException - if the input JSON structure does not match object structure

Usage example (jsonString is the input string):

Model fromJson = objectMapper.readValue(jsonString, Model.class);

Method for serialization:

String writeValueAsString(Object value)

  • Throws
    • JsonProcessingException in case of an error
    • Note: prior to version 2.1, throws clause included IOException; 2.1 removed it.