2020년 5월 12일 화요일

[Spring] Respond ajax using Gson in the Spring

Why use Gson?

  On websites, clients and servers request and respond to each other via ajax. The request information sent in the form of a JSON Object should be received from the controller, processed several times, and then sent back the response information. Because ajax only receives response information in the form of a string, the controller must send a map or command object into the JSON Object string. In this situation, Gson allows you to make multiple objects into JSON Object strings.

Using Gson in the Spring

pom.xml
<!-- Gson -->
<dependency>
 <groupId>com.google.code.gson</groupId>
 <artifactId>gson</artifactId>
 <version>2.8.5</version>
</dependency>

toJson, fromJson Methods

 As a method in the Gson library, you can convert objects to JSON Object strings and JSON Object to a different type.

Basic Usage
Gson gson = new Gson();

// Object를 JSON Object 문자열로 반환
gson.toJson(Object)

// JSON Object를 해당 타입으로 바꿈
gson.fromJson(jsonObject, Class);

example
HashMap<String, Object> map = new HashMap<String, Object>();
JsonObject jsonObject = new JsonObject();

// Gson 객체 생성
Gson gson = new Gson();

// 맵을 JSON Object 문자열로 바꿈
String jsonString = gson.toJson(map);

// JSON Object를 맵으로 바꿈
gson.fromJson(jsonObject, new HashMap<String, Object>().getClass());  

Send VO Object to JSON

Controller
@ResponseBody
@RequestMapping(value = "/url", method = RequestMethod.POST)
public String questLoad(QuestVO questVO, Model model) throws Exception {
   
    List<QuestVO> questList = questService.selectQuestList(questVO);
  
    Gson gson = new Gson();
    HashMap<String, Object> map = new HashMap<String, Object>();
    
    // key-value 형태로 맵에 저장
    map.put("questList", questList);
   
   // 맵을 JSON Object를 바꾸고 다시 문자열로 바꿈
    String jsonString = gson.toJson(map);
  
    return jsonString;
}
 JSON Object requires a Property to be created, so you declare the map and add the Property and Value. Then use the toJson method to change the map to JSON Object string.

Ajax
$.ajax({
    url: "/url",
    type: "post",
    success: function(data) {  
        var obj = JSON.parse(data);
        
        /* obj = {"questList": ["questId": 1, "questTitle": "a"],
                               ["questId": 2, "questTitle": "b"]
                 }
         */       
        console.log(obj.questList[0].questId);
        // 1 출력
    },
    error: function(errorThrown) {
        alert(errorThrown);
    },
});
Request ajax to execute the controller method. The jsonString returned by the above method enters the data, which is the parameter of the access callback function. If you convert JSON.parse to JSON Object, you will be able to access the project.

댓글 없음:

댓글 쓰기