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 content