ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JAVA] JSON library Jackson 사용법
    Java/기타 2019. 5. 14. 15:32
    반응형

    Jackson 이란?

    Java Object를 JSON으로 변환하거나 JSON을 Java Object로 변환하는데 사용할 수 있는 Java 라이브러리입니다.

    Jackson Github - https://github.com/FasterXML/jackson

     

    Jackson 특징

    1.Stream API : 스트림 형식으로 데이터를 분석하고 생성하기 때문에 성능이 좋습니다.

    2.Tree Model : XML의 DOM 처럼 Node 형태로 데이터를 다룰 수 있기 때문에 유연성이 좋습니다.

    3.Data Binding : POJO 기반의 자바 객체들을 JSON으로 변환시킬 수 있습니다.

     

    Maven 설정

     jackson-databind 라이브러리는 jackson-core 및 jackson-annotation 라이브러리의 의존성을 포함하기 때문에 메이븐을 사용하는 경우 jackson-databind 라이브러리만 추가해주시면 됩니다.

    1
    2
    3
    4
    5
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.8</version>
    </dependency>
    cs

    Maven Repository : https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind

     

    객체를 JSON으로 변환

    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
    package com.tychejin.study.json;
     
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
     
    import com.fasterxml.jackson.core.JsonGenerationException;
    import com.fasterxml.jackson.databind.JsonMappingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
     
    public class JacksonExample01 {
     
        public static void main(String[] args) {
     
            ObjectMapper mapper = new ObjectMapper();
     
            User user = setUser();
     
            try {
     
                // 객체를 JSON 타입의 파일로 변환
                mapper.writeValue(new File("c:\\user.json"), user);
     
                // 객체를 JSON 타입의 String으로 변환
                String jsonInString01 = mapper.writeValueAsString(user);
                System.out.println(jsonInString01);
     
                // 객체를 JSON 타입의 String으로 변환 및 정렬
                String jsonInString02 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
                System.out.println(jsonInString02);
     
            } catch (JsonGenerationException e) {
                e.printStackTrace();
            } catch (JsonMappingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
     
        public static User setUser() {
     
            User user = new User();
            user.setName("JSON");
            user.setAge(10);
     
            List<String> list = new ArrayList<String>();
            list.add("JSON은 자바스크립트를 확장하여 만들어졌습니다.");
            list.add("JSON은 자바스크립트 객체 표기법을 따릅니다.");
            list.add("JSON은 사람과 기계가 모두 읽기 편하도록 고안되었습니다.");
            list.add("JSON은 프로그래밍 언어와 운영체제에 독립적입니다.");
            user.setMessages(list);
            
            return user;
        }
    }
     
    cs

     

    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
    package com.tychejin.study.json;
     
    import java.util.List;
     
    public class User {
     
        private String name;
        private int age;
        private List<String> messages;
     
        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 List<String> getMessages() {
            return messages;
        }
     
        public void setMessages(List<String> messages) {
            this.messages = messages;
        }
        
        @Override
        public String toString() {
            
            String result = "";
                    
            result = "[name:"+ name + ",age:"+ age +",messages:"+ messages +"]";
            
            return result;        
        }
    }
     
    cs

     

    JSON을 Java Object로 변환

    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
    package com.tychejin.study.json;
     
    import java.io.File;
    import java.io.IOException;
     
    import com.fasterxml.jackson.core.JsonGenerationException;
    import com.fasterxml.jackson.databind.JsonMappingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
     
    public class JacksonExample02 {
     
        public static void main(String[] args) {
     
            ObjectMapper mapper = new ObjectMapper();
     
            try {
                
                // JSON 타입의 파일을 객체로 변환
                User user01 = mapper.readValue(new File("c:\\user.json"), User.class); 
                System.out.println(user01);
                            
                String jsonInString = "{\"name\":\"JSON\",\"age\":10,\"messages\":[\"JSON은 자바스크립트를 확장하여 만들어졌습니다.\",\"JSON은 자바스크립트 객체 표기법을 따릅니다.\",\"JSON은 사람과 기계가 모두 읽기 편하도록 고안되었습니다.\",\"JSON은 프로그래밍 언어와 운영체제에 독립적입니다.\"]}";
                
                // JSON 타입의 String을 객체로 변환
                User user02 = mapper.readValue(jsonInString, User.class);
                System.out.println(user02);
                
            } catch (JsonGenerationException e) {
                e.printStackTrace();
            } catch (JsonMappingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
     
    cs

     

    JSON 변환 (String, Map, List, JSONString, JSONObject, JSONArray) - https://tychejin.tistory.com/311

     

    반응형

    댓글

Designed by Tistory.