Language/JAVA

JAVA JSON 라이브러리 Jackson 사용법

적외선 2014. 11. 27. 15:19

참조 :  
1. http://jackson.codehaus.org/
2. http://wiki.fasterxml.com/JacksonInFiveMinutes

라이브러리 다운로드
http://wiki.fasterxml.com/JacksonDownload
jackson-core, jackson-databind, jackson-annotations 를 다운 받음.

Jackson 에서 JSON 처리에 제공하는 방법
1. Streaming API
     성능이 빠름.
2. Tree Model
     일반적인 XML처럼 노드형태로 Json 데이터를 다룸. 유연성이 가장 좋음. 입맛대로 구성할 수 있음.
3. Data Binding
     POJO 기반의 가자 객체들을 JSON으로 변환함.
   -Simple data Binding : 자바클래스 내의 Map, List, String, 숫자형, Boolean, null 형의 데이터들을 JSON으로 변환함.
   -Full data binding : Simple data Binding에서 제공하는것들을 포함하고 자바 빈타입에서 제공하는 데이터들도 JSON으로 변환함.


소스
* 공식사이트에 있는 import 패키지 이름이 버전업되면서 변경됐음.(2013-05-22)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
 
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
 
 
public class testJacksonJSON {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
 
         
        try {
 
            ObjectMapper mapper = new ObjectMapper(); // 재사용 가능하고 전체코드에서 공유함.
 
 
            String user_json = "{\"name\" : { \"first\" : \"Joe\", \"last\" : \"Sixpack\" }, "
                    " \"gender\" : \"MALE\", "
                    " \"verified\" : false, "
                    " \"userImage\" : \"Rm9vYmFyIQ==\" " "      } ";
 
            User user = mapper.readValue(user_json, User.class);
             
            System.out.println("First name : " + user.getName().getFirst());
            System.out.println("Last name : " + user.getName().getLast());
            System.out.println("Gender : " + user.getGender());
            System.out.println("Verified : " + user.isVerified());
 
            user.getName().setFirst("ChangeJoe");
            user.getName().setLast("ChangeSixpack");
             
            String jsonStr = mapper.writeValueAsString(user);
            System.out.println("Simple Binding : "+jsonStr);
             
            //직접 raw 데이터를 입력해서 JSON형태로 출력하는 방법.
            Map<string,object> userData = new HashMap<string,object>();
            Map<string,string> nameStruct = new HashMap<string,string>();
            nameStruct.put("first""RawJoe");
            nameStruct.put("last""Sixpack");
            userData.put("name", nameStruct);
            userData.put("gender""MALE");
            userData.put("verified", Boolean.FALSE);
            userData.put("userImage""Rm9vYmFyIQ==");
             
            jsonStr = mapper.writeValueAsString(userData);
            System.out.println("Raw Data : "+jsonStr);
             
            //Tree 모델 예제
            ObjectMapper m = new ObjectMapper();
            // mapper.readTree(source), mapper.readValue(source, JsonNode.class); 둘중 하나 사용가능.
            JsonNode rootNode = m.readTree(user_json);
 
            JsonNode nameNode = rootNode.path("name");
            String lastName = nameNode.path("last").textValue();
            ((ObjectNode)nameNode).put("last""inputLast");
             
            jsonStr = m.writeValueAsString(rootNode);
            System.out.println("Tree Model : "+jsonStr);
             
             
            //Streaming API 예제
            JsonFactory f = new JsonFactory();
             
            OutputStream outStr = System.out;
 
            JsonGenerator g = f.createJsonGenerator(outStr);
 
            g.writeStartObject();
            g.writeObjectFieldStart("name");
            g.writeStringField("first""StreamAPIFirst");
            g.writeStringField("last""Sixpack");
            g.writeEndObject(); // 'name' 필드용.
            g.writeStringField("gender""MALE");
            g.writeBooleanField("verified"false);
            g.writeFieldName("userImage");
            g.writeEndObject();
            g.close(); // 사용한 다음 close해줘서 output에 있는 내용들을 flush해야함.
             
             
        catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        catch (IOException e) {
            // TODO Auto-generated catch block
        e.printStackTrace();
        }
         
         
    }
 
}
 
class User {
    public enum Gender { MALE, FEMALE };
 
    public static class Name {
      private String _first, _last;
 
      public String getFirst() { return _first; }
      public String getLast() { return _last; }
 
      public void setFirst(String s) { _first = s; }
      public void setLast(String s) { _last = s; }
    }
 
    private Gender _gender;
    private Name _name;
    private boolean _isVerified;
    private byte[] _userImage;
 
    public Name getName() { return _name; }
    public boolean isVerified() { return _isVerified; }
    public Gender getGender() { return _gender; }
    public byte[] getUserImage() { return _userImage; }
 
    public void setName(Name n) { _name = n; }
    public void setVerified(boolean b) { _isVerified = b; }
    public void setGender(Gender g) { _gender = g; }
    public void setUserImage(byte[] b) { _userImage = b; }
}
</string,string></string,string></string,object></string,object>


출처 - http://arisu1000.tistory.com/27710