반응형


마지막으로 hashmap 을 json으로 만드는 방법과, JsonObject를 생성하는 방법이다.



Spring boot Json 1편, 2편, 3편, 4편

1. 2018/11/06 - [Spring Boot] - Spring Boot Json, JsonObject로 만들기 - JSON 1편

2. 2018/11/07 - [Develop/Spring Boot] - Spring Boot Json, Gson을 이용한 JsonObject to String, String to JsonObject- JSON 2편

3. 2018/11/09 - [Develop/Spring Boot] - Spring Boot Json, Jackson을 이용한 JsonParsing - Json 3편

4. 2018/11/12 - [Develop/Spring Boot] - Spring Boot Deserialization Json, Deserialization JsonString to JsonObject - Json 4편



번외 Database의 값을 Json으로 select하는 방법.

1. 2018/10/24 - [Spring Boot] - Spring boot jpa map, hashmap, JSON형식

2. 2018/10/28 - [Spring Boot] - Spring boot JPA EntityManager를 이용한 Map형식으로 mapping하기


Spring boot에서 MySQL JSON 타입 SELECT하는 방법

1. 2018/11/30 - [Develop/Spring Boot] - Spring boot MySQL JSON - MySQL JSON DATA TYPE 값 가져오기



HashMap을 Json으로 만드는 방법을 배우기에 앞서 JsonObject를 생성하는 방법을 먼저 본다.


1. google-json-simple을 이용한 JsonObject 만드는 방법.


xml에 아래와 같은 dependency를 추가한다.

1
2
3
4
5
<dependency>
        <groupid>com.googlecode.json-simple</groupid>
        <artifactid>json-simple</artifactid>
        <version>1.1</version>
</dependency>


우리가 만들어볼 Json예제는 4편에서 사용한 Json이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
{
    "id": 1,
    "password": "1234",
    "details": [
        {
            "name": "test",
            "age": 20
        },{
            "name": "test2",
            "age": 21
        }
    ]
}

그리고 아래와 같이 JSONObject라는 것과 JSONArray라는 것을 사용하여 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
public void test() {
        JSONObject obj = new JSONObject();
        JSONArray arr = new JSONArray();
         
        obj.put("id", 1);
        obj.put("password", "1234");
         
        JSONObject obj2 =new JSONObject();
        obj2.put("name", "test");
        obj2.put("age", 20);
         
        arr.add(obj2);
         
        obj2 = new JSONObject();
        obj2.put("name", "test2");
        obj2.put("age", 21);
         
        arr.add(obj2);
         
        obj.put("details", arr);
         
        System.out.println(obj.toString());
         
}




현재는 Json이 Array를 포함하여 JSONArray를 사용하였지만 일반 적인 key : value 형태는 JSONObject 하나만으로도 생성할 수 있다.


2. Gson을 이용한JsonObject 생성


이 방법은 Json  2편에서 배웠으나 이번엔 Array를 사용하기 때문에 다시 한번 해본다. 사실 위의 json-simple과 별반 다를게 없다.



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
public void test() {
    Gson gson = new Gson();
    JsonObject obj = new JsonObject();
    JsonArray arr = new JsonArray();
     
    obj.addProperty("id", 1);
    obj.addProperty("password", "1234");
     
    JsonObject obj2 = new JsonObject();
    obj2.addProperty("name", "test");
    obj2.addProperty("age", 20);
    arr.add(obj2);
     
    obj2= new JsonObject();
    obj2.addProperty("name", "test2");
    obj2.addProperty("age", 21);
     
    arr.add(obj2);
     
    obj.add("details", arr);
     
    String jsonString = obj.toString();
     
    System.out.println("gson을 이용한 객체생성");
    System.out.println(jsonString);
     
}




3. HashMap을 Json으로 만드는 방법.


HashMap<String, Object>를 선언해서 이번 편에서 했던 모든 것들(json-simple의 obj와 gson의 obj)을 HashMap에 put해보고

일반 데이터를 HashMap에 put해서 json으로 변환해 보는 법을 해본다. 그리고 gson의 prettyprinting을 이용하여 예쁘게 출력해본다.



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
public void test() {
        JSONObject obj = new JSONObject();
        JSONArray arr = new JSONArray();
 
        obj.put("id", 1);
        obj.put("password", "1234");
 
        JSONObject obj2 = new JSONObject();
        obj2.put("name", "test");
        obj2.put("age", 20);
 
        arr.add(obj2);
 
        obj2 = new JSONObject();
        obj2.put("name", "test2");
        obj2.put("age", 21);
 
        arr.add(obj2);
 
        obj.put("details", arr);
 
         
        JsonObject g_obj = new JsonObject();
        JsonArray g_arr = new JsonArray();
 
        g_obj.addProperty("id", 1);
        g_obj.addProperty("password", "1234");
 
        JsonObject g_obj2 = new JsonObject();
        g_obj2.addProperty("name", "test");
        g_obj2.addProperty("age", 20);
        g_arr.add(g_obj2);
 
        g_obj2 = new JsonObject();
        g_obj2.addProperty("name", "test2");
        g_obj2.addProperty("age", 21);
 
        g_arr.add(g_obj2);
 
        g_obj.add("details", g_arr);
         
        HashMap<string, object=""> map = new HashMap<string, object="">();
        map.put("json-simple", obj);
        map.put("gson", g_obj);
        map.put("HashMap", "맵테스트");
        map.put("숫자테스트", 1234567890);
         
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String jsonString = gson.toJson(map, new TypeToken<map<string, object="">>() {
        }.getType());
        System.out.println("HashMap to JSON");
        System.out.println(jsonString);
 
    }
</map<string,></string,></string,>



이로써 Spring boot 에서의 Json에 대한 학습을 마무리한다.

1편부터 마지막편까지의 내용과 번외편 내용 2개만 알아도 Spring boot에서 모든 데이터들을 Json으로 만들 수 있다.


반응형
반응형

JPA ORM을 이용한 @Query의 결과값을 Map, JSON형식으로 바로 만들어주는 방법은 2가지가 있다


1. Map을 이용한다.

2. DTO(POJO, VO)를 생성하여 이용한다.



JPA EntityManager를 이용한 Map형식으로 Mapping하는 방법은 아래 링크에 있다.

1. 2018/10/28 - [Develop/Spring Boot] - Spring boot JPA EntityManager를 이용한 Map형식으로 mapping하기




Spring Boot Json익히기

Spring boot Json 1편, 2편, 3편, 4편, 마지막

1. 2018/11/06 - [Develop/Spring Boot] - Spring Boot Json, JsonObject로 만들기 - JSON 1편

2. 2018/11/07 - [Develop/Spring Boot] - Spring Boot Json, Gson을 이용한 JsonObject to String, String to JsonObject- JSON 2편

3. 2018/11/09 - [Develop/Spring Boot] - Spring Boot Json, Jackson을 이용한 JsonParsing - Json 3편

4. 2018/11/12 - [Develop/Spring Boot] - Spring Boot Deserialization Json, Deserialization JsonString to JsonObject - Json 4편

5. 2018/11/13 - [Develop/Spring Boot] - Spring Boot Json, hashmap to json , JsonObject 만들기- JSON 마지막



Spring boot에서 MySQL JSON 타입 SELECT하는 방법

1. 2018/11/30 - [Develop/Spring Boot] - Spring boot MySQL JSON - MySQL JSON DATA TYPE 값 가져오기



1. Map을 이용.

 

(html편집기가 자꾸 안되서 사진으로 대체합니다)


select 문 안에 new map을 선언한다. 주의할 점으로는 as를 사용하지않으면 Map의 Key값에 숫자가 들어간다. 예를들면 만약 저 위의 코드에 as를 주지 않는다면 {0 : id, 1 : password}라는 숫자가 0부터 증가하는 형식으로 들어가게 되며 as를 주게되면 as 로 선언한 이름이 Key값으로 들어간다. 

 2. DTO(POJO, VO)를 이용하는 방법. 먼저 패키지를 생성하고 DTO(POJO, VO)를 생성한다 ex) net.test.com // 패키지안에 TestDTO.java 생성
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class TestDTO{
   private String id;
   private String password;
 
   public TestDTO(){}
 
   public Test(String id, String password){
        this.id = id;
        this.password=password;
   }
   public String getId(){
         return id;
   }
   public void setId(String id){
         this.id =id;
   }
 
   public String getPassword(){
         return password;
   }
   public void setPassword(String password){
         this.password =password;
   }
}
주의할점은 디폴트 생성자를 필수적으로 생성해줘야 한다. 이후
1
2
3
4
5
6
7
8
@Query("select new  net.test.com.TestDTO(t.test_id, t.test_password) from Test t")
    List<testdto> test();
 
//위의 값을 가져오는 방법.
List<testdto> t = testDAO.test();
t.getId()
 
</testdto></testdto>
1번의 Map과 다르게 as를 설정하지 않아도 {id : id} 값으로 잘 받을 수 있다. 하지만 일일이 DTO(POJO, VO) 를 생성해야 하는 번거로움이 존재.


반응형

+ Recent posts