@JsonTypeInfo (+@JsonSubTypes) 3편 (심화) - JSON -> Object

주야·2024년 4월 8일

지난 시간에 Object -> Json 변환 했다.
1탄 보러가기
2탄 보러가기


이번 시간에는 Json -> Object로 변환 할 차례이다.

선언해 놓은 ObjectMapper를 통해서 Json을 Object로 변환한다.

JSON을 Object로 변환

ObjectMapper.readValue (String content, ClassvalueType);

Object를 JSON으로 변환

ObjectMapper.writeValueAsString(Object value)

실제 JSON형태로 데이터를 변환한 경험이 적어서 어렵게만 생각했는데, ObjectMapper를 이용하면 매우 쉽게 변환이 가능하다.

실제 프로젝트에 어떠헥 쓰일지 모르겠으나, 예상해보면 다음과 같지 않을 까 추측한다.

  • DB History table에서 꺼내온 Json 형태의 데이터를 화면에 노출시킨다.

  • 아래 readValue첫번째 매개변수인 result는 DB 조회 후 가져온 결과로 String(JSON)타입이고

  • HistoryDto객체에 Json형태 String 데이터를 역직렬화 후 담은 후 Model에 싣어서 화면단으로 보낸다.

    HistoryDto historyDto = om.readValue(result, HistoryDto.class);
    model.addAttribute("historyDto", historyDto);
    
  • 화면에서는 아래와 같이 받아주면 됨.

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>historyDetail</title>
    </head>
    <body>
    <div>
      <th:block th:if="${historyDto != null}">
          <table>
              <tr>
                  <th scope="col">index</th>
                  <th scope="col">Type</th>
                  <th scope="col">변경 전</th>
                  <th scope="col">변경 후</th>
              </tr>
              <th:block th:each="item : ${historyDto.getChanges()}">
                      <tr>
                          <td th:text="${historyDto.getIndex()}"></td>
                          <td th:text="${item.getName()}"></td>
                          <td th:text="${item.getOldValue()}"></td>
                          <td th:text="${item.getNewValue()}"></td>
                      </tr>
              </th:block>
          </table>
      </th:block>
    </div>
    </body>
    </html>
    

결과

HistoryDto changes가 List 형태라서 뭔가 추가적인 작업을 해줘야한다고해서 헤맸는데,
일단 Json을 그냥 바로 넣으니 필드에 자동 맵핑이 된다.

HistoryDto.class


@Data
@ToString
public class HistoryDto {
  private int index;
  private List<Captured> changes = new ArrayList<>();

  public void addIfChanged(Captured change) {
      if(change.changed()) {
          changes.add(change);
      }
  }

}

직렬화/역직렬화 다형성을 위해 @JsonTypeInfo가 왜 필요한지 모르겠다... 타입매칭없이도 역직렬화 잘만되고, 화면단에서 데이터도 잘 가져와진다... 흠 알다가도 모르겠다...

profile
개발자

0개의 댓글