Java JsonNode get과 path 차이

@ZungTa · 2024-01-18 목요일 · 2 min read

Jackson 패키지에서 JsonNode를 사용할 때 오브젝트의 value를 가져오는 방법 중 주로 사용하는 2가지가 있다.

get 메서드와 path 메서드인데 사용 방법은 똑같지만 몇 가지 차이점이 있는 것 같은데 오늘 살펴볼 내용은 없는 key를 가져올 때의 차이를 살펴본다.

결론부터 말하면 path를 사용하는게 낫다.

기본 데이터

예시로 데이터를 이렇게 준비했다.

ObjectMapper objectMapper = new ObjectMapper();
String jsonData = """
    {
      "users": [
        {
          "profile": {
            "name": "john",
            "age": 11
          }
        }
      ]
    }
    """;
JsonNode users = objectMapper.readTree(jsonData);

없는 key를 가져올 때

  • get: null
  • path: MissingNode
// null
JsonNode nodeWithGet = users.get("person");

// MissingNode
JsonNode nodeWithPath = users.path("person");

depth get

path 사용 시 null이 아니라 MissingNode를 반환하는데 이것의 유용함은 깊은 값을 가져올 때 알 수 있다.

path는 없는 key를 가져오더라도 에러 없이 계속해서 path를 통해서 값을 가져오는 것이 가능하다.

1 depthget 해서 null 검사하고 반복하는 것을 안 해도 된다.

// NPE (NullPointerException)
JsonNode nodeWithGet = users.get("person").get("profile").get("name");

// MissionNode
JsonNode nodeWithPath = users.path("person").path("profile").path("name");

없는 value 변환

  • get: NPE (NullPointerException)
  • path: 기본 값
// NPE (NullPointerException)
Integer ageWithGet = users.get("users").get(0).get("profile").get("agee").asInt();

// 0
Integer ageWithPath = users.path("users").path(0).path("profile").path("agee").asInt();

null 체크

  • get: Objects.isNull, ≠ null로 검사
  • path: isMissingNode로 검사

    • 해당 key가 아예 없는 경우는 MissingNode가 된다.
    • 해당 key의 value 값으로 null이 들어가 있다면 MissingNode는 되지 않고 NullNode가 된다.
      이런 경우에는 isNull로 검사할 수 있다.
JsonNode nodeWithGet = users.get("person");
boolean isNullNode = Objects.isNull(nodeWithGet);

JsonNode nodeWithPath = users.path("person");
boolean isMissingNode =  nodeWithPath.isMissingNode();
boolean isNull = nodeWithPath.isNull();
@ZungTa
I'm a backend developer
© ZungTa Devlog, Built with Gatsby