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

Hollo.java
package sample.jackson;    public class Hollo {        public int id;        public String name;        @Override    public String toString() {        return "Hello [id=" + id + ", name=" + name + "]";    } } 
Main.java
package sample.jackson;import java.io.IOException;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);    }}
OUTPUT:
Hello [id = 20, name = TOM]


Note:

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(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1106)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:296)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:133)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3736)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2726)
at sample.jackson.Main(Main.java:18)