1. Reader 사용
요청 데이터로 들어온 JSON 데이터를 받아들이기 위해 Reader를 사용한다. 내 경우에는 BufferedReader를 사용해 JSON 데이터를 받았다.
private void myServlet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedReader br = request.getReader();
String jsonData = br.readLine();
}
2. Gson 사용
다음은 문자열로 받은 JSON 데이터를 Map으로 변환한다. 내 경우에는 Gson 라이브러리를 사용했다.
import java.util.Map;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = gson.fromJson(jsonData, type);
3. Map처럼 사용하기
Map으로 변환이 완료되었으므로 get() 메서드를 사용해 값을 꺼내어 사용하면 된다.
String userId = map.get("userId");
'웹 개발 > 웹 개발' 카테고리의 다른 글
쿠키(Cookie) (0) | 2023.01.18 |
---|---|
세션(Session) (0) | 2023.01.18 |
필터를 사용한 로그 파일 생성 (0) | 2023.01.17 |
HttpServletRequest getServletPath() 와 getPathInfo() 의 차이 (0) | 2023.01.17 |
자바 웹 소켓을 이용한 채팅 서버 (0) | 2023.01.12 |