21장. JsonPath

21.1. 개요

JsonPath 언어는 JSON 메시지의 일부를 추출하기 위한 편리한 구문을 제공합니다. JSON 구문은 Cryostat와 유사하지만 XML에서 작동하는 대신 JSON 메시지에서 JSON 오브젝트를 추출하는 데 사용됩니다. jsonpath DSL 명령은 표현식 또는 서술자로 사용할 수 있습니다(이 경우 빈 결과가 부울 false로 해석됨).

21.2. JsonPath 패키지 추가

Camel 경로에서 JsonPath를 사용하려면 다음과 같이 camel-jsonpath 에 대한 종속성을 프로젝트에 추가해야 합니다.

<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-jsonpath</artifactId>
  <version>${camel-version}</version>
</dependency>

21.3. Java 예

다음 Java 예제에서는 jsonpath() DSL 명령을 사용하여 특정 가격 범위에서 항목을 선택하는 방법을 보여줍니다.

from("queue:books.new")
  .choice()
    .when().jsonpath("$.store.book[?(@.price < 10)]")
      .to("jms:queue:book.cheap")
    .when().jsonpath("$.store.book[?(@.price < 30)]")
      .to("jms:queue:book.average")
    .otherwise()
      .to("jms:queue:book.expensive")

JsonPath 쿼리에서 빈 세트를 반환하는 경우 결과가 false 로 해석됩니다. 이렇게 하면 JsonPath 쿼리를 서술자로 사용할 수 있습니다.

21.4. XML 예

다음 XML 예제에서는 jsonpath DSL 요소를 사용하여 경로에 서술자를 정의하는 방법을 보여줍니다.

<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
  <route>
    <from uri="direct:start"/>
    <choice>
      <when>
        <jsonpath>$.store.book[?(@.price < 10)]</jsonpath>
        <to uri="mock:cheap"/>
      </when>
      <when>
        <jsonpath>$.store.book[?(@.price < 30)]</jsonpath>
        <to uri="mock:average"/>
      </when>
      <otherwise>
        <to uri="mock:expensive"/>
      </otherwise>
    </choice>
  </route>
</camelContext>

21.5. 쉬운 구문

jsonpath 구문을 사용하여 기본 서술자를 정의하려는 경우 구문을 기억하는 것이 다소 어려울 수 있습니다. 예를 들어 모든 저렴한 서적을 찾으려면 다음과 같이 구문을 작성해야 합니다.

$.store.book[?(@.price < 20)]

그러나 다음과 같이 작성할 수 있는 경우 어떻게 해야 합니까?

store.book.price < 20

price 키가 있는 노드를 확인하려는 경우 경로를 생략할 수도 있습니다.

price < 20

이를 지원하기 위해 기본 스타일을 사용하여 서술자를 정의하는 데 사용하는 easyPredicateParser 가 있습니다. 즉, 서술자는 $ 기호로 시작하지 않아야 하며 하나의 연산자만 포함해야 합니다. 쉬운 구문은 다음과 같습니다.

left OP right

올바른 Operator에서 Camel 간단한 언어를 사용할 수 있습니다. 예를 들면 다음과 같습니다.

store.book.price < ${header.limit}

21.6. 지원되는 메시지 본문 유형

Camel JSonPath는 다음 유형을 사용하여 메시지 본문을 지원합니다.

유형설명

파일

파일에서 읽기

문자열

일반 문자열

map

essage body as java.util.Map 유형

list

Message body as java.util.List 유형

POJO

jackson이 classpath에 있는 경우 camel-jsonpath 는 jackson을 사용하여 메시지 본문을 Cryostat로 읽고 JSonPath에서 지원하는 java.util.Map 으로 변환할 수 있습니다. 예를 들어 jackson을 포함하기 위해 camel-jackson 을 종속성으로 추가할 수 있습니다.

InputStream

위의 유형이 일치하지 않는 경우 Camel은 메시지 본문을 java.io.InputStream 으로 읽으려고 합니다.

메시지 본문이 지원되지 않는 형식인 경우 기본적으로 예외가 발생하지만 JSonPath를 구성하여 예외를 억제할 수 있습니다.

21.7. 예외 비활성화

jsonpath 표현식에서 구성한 경로를 찾을 수 없는 경우 JSONPath가 예외를 throw합니다. SuppressExceptions 옵션을 true로 설정하여 예외를 무시할 수 있습니다. 예를 들어 아래 코드에서 jsonpath 매개변수의 일부로 true 옵션을 추가합니다.

from("direct:start")
    .choice()
        // use true to suppress exceptions
        .when().jsonpath("person.middlename", true)
            .to("mock:middle")
        .otherwise()
            .to("mock:other");

XML DSL에서 다음 구문을 사용합니다.

<route>
  <from uri="direct:start"/>
  <choice>
    <when>
      <jsonpath suppressExceptions="true">person.middlename</jsonpath>
      <to uri="mock:middle"/>
    </when>
    <otherwise>
      <to uri="mock:other"/>
    </otherwise>
  </choice>
</route>

21.8. JSONPath 삽입

Cryostat 통합을 사용하여 Quarkus 메서드를 호출할 때 JsonPath를 사용하여 메시지에서 값을 추출하고 메서드 매개 변수에 바인딩할 수 있습니다. 예를 들면 다음과 같습니다.

// Java
public class Foo {

    @Consume(uri = "activemq:queue:books.new")
    public void doSomething(@JsonPath("$.store.book[*].author") String author, @Body String json) {
      // process the inbound message here
    }
}

21.9. 인라인 간단한 표현식

Camel 2.18의 새로운 기능.

Camel은 JsonPath 표현식에서 인라인 단순 표현식을 지원합니다. 간단한 언어 삽입은 다음과 같이 간단한 구문으로 표현해야 합니다.

from("direct:start")
  .choice()
    .when().jsonpath("$.store.book[?(@.price < `${header.cheap}`)]")
      .to("mock:cheap")
    .when().jsonpath("$.store.book[?(@.price < `${header.average}`)]")
      .to("mock:average")
    .otherwise()
      .to("mock:expensive");

아래 표시된 대로 allow Simple =false 옵션을 설정하여 단순 표현식에 대한 지원을 끕니다.

Java:

// Java DSL
.when().jsonpath("$.store.book[?(@.price < 10)]", false, false)

XML DSL:

// XML DSL
<jsonpath allowSimple="false">$.store.book[?(@.price &lt; 10)]</jsonpath>

21.10. reference

JsonPath에 대한 자세한 내용은 JSonPath 프로젝트 페이지를 참조하십시오.