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}
Import statement needed:
import com.fasterxml.jackson.databind.ObjectMapper;
Maven dependency: jackson-databind
ObjectMapper
instance//creating one
ObjectMapper objectMapper = new ObjectMapper();
ObjectMapper
is threadsafe<T> T readValue(String content, Class<T> valueType)
valueType
needs to be specified -- the return will be of this typeIOException
- in case of a low-level I/O problemJsonParseException
- if underlying input contains invalid contentJsonMappingException
- if the input JSON structure does not match object structureUsage example (jsonString is the input string):
Model fromJson = objectMapper.readValue(jsonString, Model.class);
String writeValueAsString(Object value)
JsonProcessingException
in case of an error