JSON(JavaScript Object Nation)

  • XML 같은 테이터 표현 방법
  • name과 value의 값으로 구성
  • 이기종간의 데이터 전달을 위해서 사용
  • XML보다 JSON이 크기가 적다(XML태그가 없어서)
  • 사람이 읽고 쓰기에 용이하다
  • 개발 언어와 OS에 구애 받지 않는다
  • 사용예제 {“name” : “google”, “url”:”www.google.com”}

json 라이브러리 세팅

  • commons-beanutils.jar
  • commons-collections-3.2
  • commons-lang-2.4
  • commons-logging-1.1
  • ezmorph-1.0.6
  • json_simple-1.1
  • json-lib-2.3-jdk13

Source

  • 객체 ->JSON , JSON -> 객체로 변환

JsonExam.java


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;


public class JsonExam {

    // JSONObject => json code
    // {"name" : "홍길동", "address" : "가산동", "age":20}
    public JSONObject creatJsonObject(){
        JSONObject obj = new JSONObject();
        obj.put("name", "홍길동");
        obj.put("address", "가산동");
        obj.put("age", 20);
        
        return obj;
    }
    
    public JSONObject creatJsonObject2(){
        JSONObject obj2 = new JSONObject();
        obj2.put("name", "좌길동");
        obj2.put("address", "강남");
        obj2.put("age", 40);
        
        return obj2;
    }
    
    public static void main(String[] args){
        // 일반코드->json 객체로
        JsonExam exam = new JsonExam();
        JSONObject obj = exam.creatJsonObject();
        JSONObject obj2 = exam.creatJsonObject();
        //System.out.println("result:"+obj.toJSONString());
        //System.out.println("result:"+obj2.toJSONString());
    
        // json 데이터를 배열에 담는다
        JSONArray ja = new JSONArray();
        ja.add(obj);
        ja.add(obj2);
        
        // JSONArray => json code
        System.out.println(ja.toJSONString());
        
        // List => json code 변환 [{"key:",value},{"key":value}]
        List<Member> list = new ArrayList<>();
        list.add(new Member("홍길동", "가산동", 20));
        list.add(new Member("동길이", "구로동", 40));
        System.out.println(net.sf.json.JSONArray.fromObject(list).toString());
        
        // Json 데이터 -> String
        String jsonCode = net.sf.json.JSONArray.fromObject(list).toString();    // list객체를 json으로 변환
        JSONParser parser = new JSONParser();
        Object re = null;
        
        try{
            re = parser.parse(jsonCode);// json 코드를 파싱하겠다
        }catch(Exception e){
            e.printStackTrace();
        }
        
        if(re instanceof JSONArray){
            JSONArray array = (JSONArray)re;
            Iterator iter = array.iterator();
            List<Member> list2 = new ArrayList<>();
            
            while(iter.hasNext()){
                JSONObject jo = (JSONObject)iter.next();
                String name = (String)jo.get("name");
                String address = (String)jo.get("address");
                int age = ((Long)jo.get("age")).intValue();
                
                //int age2 = (int)jo.get("age"); java.lang.Long cannot be cast to java.lang.Integer 에러난다
                //System.out.println("age:"+age2);
                
                list2.add(new Member(name, address, age));
            }
            
            System.out.println(list2);
        }
    }
}

Member.java

public class Member {
     private String  name;
     private String  address;
     private int     age;
     
     public Member(){}
     public Member(String name, String address, int age) {
           super();
           this.name = name;
           this.address = address;
           this.age = age;
     }
     public String getName() {
           return name;
     }
     public void setName(String name) {
           this.name = name;
     }
     public String getAddress() {
           return address;
     }
     public void setAddress(String address) {
           this.address = address;
     }
     public int getAge() {
           return age;
     }
     public void setAge(int age) {
           this.age = age;
     }
     @Override
     public String toString() {
           return "Member [name=" + name + ", address=" + address  + ", age=" + age + "]";
     }
}