Looking for java Answers? Try Ask4KnowledgeBase
Looking for java Keywords? Try Ask4Keywords

Java Language Using Jackson Object Mapper


Example

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(
     "{\"firstName\":\"John\",\"lastName\":\"Doe\",\"age\":23}",
     Model.class);
System.out.println(outputObject.getFirstName());
//result: John

Example: Object to String

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

Details

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

Deserialization:

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