Convert JSON String to Java object using Jackson

JSON string → Java object

(1) Format of Class to convert  JSON  String to Java object

DTO class
public  class  DTO class  {     public  String  member name 1 ;     public  String  member name 2 ; }
Execution class
public class Main {     public static void main(String[] args) throws IOException {          String json = "JSON string";          ObjectMapper  mapper  =  new  ObjectMapper ();           DTO class  DTO instance  =  mapper . ReadValue ( json ,  DTO class . Class );          System . Out . Println ( DTO instance . Member name );      } }

(2) Driver Program To test JSON  String to Java object conversion
package sample.jackson;    public class Hollo {        public int id;        public String name;        @Override    public String toString() {        return "Hello [id=" + id + ", name=" + name + "]";    } }
package sample.jackson;import;import com.fasterxml.jackson.databind.ObjectMapper;public class Main {    public static void main(String[] args) throws IOException {        String json = "{\"id\":20, \"name\":\"TOM\"}";        ObjectMapper mapper = new ObjectMapper();        Hoge hello = mapper.readValue(json, Hello.class);        System.out.println(hello);    }}
Hello [id = 20, name = TOM]


Please do not forget to add a default connstructor in POJO class, otherwise you will get this error:

com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class sample.jackson.Info]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: {\”id\”:20, \”name\”:\”TOM\”}; line: 1, column: 2]
at com.fasterxml.jackson.databind.JsonMappingException.from(
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(
at com.fasterxml.jackson.databind.ObjectMapper.readValue(
at sample.jackson.Main(