Ga0Lee

[Java] JSON 형식으로 변환하고 전송하기 ObjectMapper & OutputStream 본문

Java

[Java] JSON 형식으로 변환하고 전송하기 ObjectMapper & OutputStream

가영리 2024. 10. 28. 13:40

ObjectMapper

Java 객체를 JSON 형식으로 변환

ObjectMapper는 Jackson 라이브러리의 클래스로, Java 객체와 JSON 간의 변환을 쉽게 해준다.

Map<String, Object> message = new HashMap<>();
message.put("message", new HashMap<String, Object>() {{
        put("token", "device-token");  // 푸시 알림을 받을 디바이스의 토큰
        put("notification", new HashMap<String, String>() {{
        put("title", "Test Title");  // 알림 제목
        put("body", "This is a test message.");  // 알림 본문
        }});
}});
            
ObjectMapper objectMapper = new ObjectMapper();
String jsonMessage = objectMapper.writeValueAsString(message);

ObjectMapper를 사용하여 message객체를 JSON 문자열로 변환하면, 아래와 같은 JSON구조가 생성된다.

{
  "message": {
    "token": "device-token",
    "notification": {
      "title": "Test Title",
      "body": "This is a test message."
    }
  }
}

OutputStream

데이터를 출력 스트림을 통해 전송할 때 사용하는 클래스

주로 HTTP 요청의 본문 (request body)에 JSON 데이터를 쓰기 위해 사용된다.

여기서 주의해야 할 점은 conn 객체의 setDoOutput(true)가 설정되어있어야 conn.getOutputStream() 메서드를 사용할 수 있다.

OutputStream outputStream = conn.getOutputStream();
outputStream.write(jsonMessage.getBytes("UTF-8"));  // JSON 문자열을 바이트로 변환하여 전송
outputStream.flush();  // 모든 데이터를 전송하고
outputStream.close();  // 스트림을 닫음 -> HTTP 요청이 서버로 전송됨