Pages

Tuesday, November 17, 2020

Jackson API - JSON String To Object In Java

1. Introduction


In this tutorial, We'll learn how to convert or transform JSON into a Java Object using Jackson API. This can be achieved in many ways using Jackson api and other GSON, JSONParser API.

Example:

String jsonString = "
 {
  "name": "nadal",
  "age": "35",
  "gender": "M"
 }";

This class needs to be converted to a Customer object.

Jackson API - JSON String To Object In Java




Maven dependency:

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-mapper-asl</artifactId>
  <version>1.9.13</version>
</dependency>

2. Create a Customer class


JSON is in string format and needs to be converted into a Customer object. First, let us create a Customer class with all attributes that JSON string has as below.

package com.java.w3schools.blog.java.program.to.jackson;

public class Customer {

 private String name;
 private int age;
 private String gender;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 public String getGender() {
  return gender;
 }

 public void setGender(String gender) {
  this.gender = gender;
 }

}

3. Converting JSON to Customer Object


Jackson API is provided with a set of classes and methods that can be used in json to java instances such as ObjectWrapper class and readValueAsString() methods.

package com.java.w3schools.blog.java.program.to.jackson;

import org.codehaus.jackson.map.ObjectMapper;

public class JSONToObjectJava {

 public static void main(String[] args) {

  String jsonString = "{    
   \"name\": \"nadal\",    
   \"age\": \"35\",
   \"gender\": \"M\" 
  }";

  ObjectMapper objectWriter = new ObjectMapper();
  
  Customer customer = objectWriter.readValue(jsonString, Customer.class);
  
  System.out.println("customer name : "+customer.getName());
  
  
 }

}

Output:

customer name : nadal

4. Conclusion


In this article, We have seen how to convert string json into java object using Jackson api. Shown the example to convert customer data as in string json into customer object.

No comments:

Post a Comment

Please do not add any spam links in the comments section.