How to convert a JSON string to a bean using JSON-lib API in Java?


The JSON-lib API is a java library to serialize and de-serialize java beans, maps, arrays, and collections in the JSON format. We need to convert a JSON string to a bean by converting a string to JSON object first then convert this to a java bean.

Syntax

public static Object toBean(JSONObject jsonObject, Class beanClass)

In the below program, we can convert a JSON string to a bean.

Example

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
public class ConvertJSONStringToBeanTest {
   public static void main(String[] args) {
      String jsonStr = "{\"firstName\": \"Adithya\", \"lastName\": \"Sai\", \"age\": 30, \"technology\": \"Java\"}";
      JSONObject jsonObj = (JSONObject)JSONSerializer.toJSON(jsonStr); // convert String to JSON
      System.out.println(jsonObj);
     
      Student student = (Student)JSONObject.toBean(jsonObj, Student.class); // convert JSON to Bean
      System.out.println(student.toString());
   }
   public static class Student {
      private String firstName;
      private String lastName;
      private int age;
      private String technology;
      public Student() {
      }
      public String getFirstName() {
         return firstName;
      }
      public void setFirstName(String firstName) {
         this.firstName = firstName;
      }
      public String getLastName() {
         return lastName;
      }
      public void setLastName(String lastName) {
         this.lastName = lastName;
      }
      public int getAge() {
         return age;
      }
      public void setAge(int age) {
         this.age = age;
      }
      public String getTechnology () {
         return technology;
      }
      public void setTechnology(String technology) {
         this.technology = technology;
     }
      public String toString() {
         return "Student[ " +
         "firstName = " + firstName +
         ", lastName = " + lastName +
         ", age = " + age +
         ", technology = " + technology +
         " ]";
      }
   }
}

Output

{"firstName":"Adithya","lastName":"Sai","age":30,"technology":"Java"}
Student[ firstName = Adithya, lastName = Sai, age = 30, technology = Java ]

Updated on: 09-Jul-2020

946 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements