How to parse JSON in Java using fasterXML / jackson-databind lib

6 months ago codedestine 0

How to parse JSON in Java :- If you had worked on restful web services, then you would have faced a problem of parsing JSON in java. JSON stands for JavaScript Object Notation, it is language independent, easy to understand, lightweight data-interchange format. JSON is a text only format, So to use it in Java, we have to parse and convert it to an object.

Let’s see how to parse JSON in Java :- 

Sample JSON

JSON for book type :-

    "language": "Java",
    "edition": "third",
    "author": "Herbert Schildt"

1) Create a class Book, this class will represent given JSON.

package com.codedestine;

public class Book {
  private int Id;
  private String Language;
  private String Edition;
  private String Author;
  public int getId() {
    return Id;
  public void setId(int id) {
    Id = id;
  public String getLanguage() {
    return Language;
  public void setLanguage(String language) {
    Language = language;
  public String getEdition() {
    return Edition;
  public void setEdition(String edition) {
    Edition = edition;
  public String getAuthor() {
    return Author;
  public void setAuthor(String author) {
    Author = author;

Jackson (Maven) :-

You can use Jackson libraries, for binding JSON String into POJO (Plain Old Java Object) instances.

Jackson is going to traverse the methods (using reflection), and maps the JSON object into the POJO instance as the field names of the class fits to the field names of the JSON object, jackson-databind library will be use for the implementation.

package com.codedestine;


import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtility {

  public static String json = "{ \"id\":\"01\", \"language\": \"Java\", \"edition\": \"third\", \"author\": \"Herbert Schildt\" }";
  public Book readJson(String json){
    Book book = null;
        ObjectMapper mapper = new ObjectMapper();
        book = mapper.readValue(json, Book.class);
    }catch(JsonMappingException e){
    }catch(JsonParseException e){
    }catch(IOException e){
    return book;
  public String writeJson(Book book){
    String json = null;
        ObjectMapper mapper = new ObjectMapper();
        json = mapper.writeValueAsString(book);
    }catch(JsonProcessingException e){
    return json;
  public static void main(String args[]){
    JsonUtility utility = new JsonUtility();
    Book book = utility.readJson(json);
    String json = utility.writeJson(book);

Result :-

How to parse Json in java

You can also check How to read and write JSON in Java using org.json 

That’s all for how to parse JSON in Java using fasterXML / jackson-databind lib. If you liked it, please share your thoughts in comments section and share it with others too.