Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java에서 JSON-lib API를 활용해 JSON 객체를 Bean으로 변환하는 방법

Java에서 JSONObject 클래스는 이름/값(name/value) 쌍으로 이루어진 순서가 없는(unordered) 컬렉션입니다. 반면 Bean은 멤버 필드에 대해 settergetter 메서드를 가지는 클래스를 의미합니다.

JSON 객체를 Bean으로 변환하려면 JSONObject 클래스가 제공하는 toBean() 메서드를 사용하면 됩니다. 이 메서드는 JSON 데이터의 키와 Bean 클래스의 필드명이 일치할 때 자동으로 값을 매핑해 줍니다.

문법(Syntax)

public static Object toBean(JSONObject jsonObject, Class beanClass)

예제 코드

아래 예제에서는 Employee 객체를 먼저 JSONObject로 변환한 뒤, 다시 toBean() 메서드를 사용하여 원래의 Bean 객체로 되돌리는 과정을 보여줍니다.

import net.sf.json.JSONObject;

public class ConvertJSONObjToBeanTest {
    public static void main(String[] args) {
        Employee emp = new Employee("Sai", "Ram", 30, "Bangalore");
        JSONObject jsonObj = JSONObject.fromObject(emp);
        System.out.println(jsonObj.toString(3)); // JSON 보기 좋게 출력(pretty print)
        emp = (Employee) JSONObject.toBean(jsonObj, Employee.class);
        System.out.println(emp.toString());
    }

    // Employee 클래스
    public static class Employee {
        private String firstName, lastName, address;
        private int age;

        public Employee() {
        }

        public Employee(String firstName, String lastName, int age, String address) {
            super();
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = age;
            this.address = address;
        }

        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 getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        @Override
        public String toString() {
            return "Employee[ " +
                    "firstName = " + firstName +
                    ", lastName = " + lastName +
                    ", age = " + age +
                    ", address = " + address +
                    " ]";
        }
    }
}

실행 결과

{
   "firstName": "Sai",
   "lastName": "Ram",
   "address": "Bangalore",
   "age": 30
}
Employee[ firstName = Sai, lastName = Ram, age = 30, address = Bangalore ]

핵심 정리

  • JSONObject.fromObject(): Java 객체(Bean)를 JSON 객체로 변환합니다.
  • JSONObject.toBean(jsonObj, Employee.class): JSON 객체를 지정한 Bean 클래스 타입의 객체로 역변환합니다.
  • 변환이 정상적으로 이루어지려면 Bean 클래스에 기본 생성자(no-arg constructor)와 각 필드에 대한 getter/setter 메서드가 반드시 정의되어 있어야 합니다.