372.5. 네임스페이스 매핑

XML에는 요소 및 속성을 완전히 충족할 수 있는 네임스페이스가 있습니다. JSON은 그렇지 않습니다. XML-JSON 변환을 수행할 때 이를 고려해야 합니다.

간격을 메우기 위해 Json-lib 에는 접두사 및 네임스페이스 URI의 형태로 네임스페이스 선언을 모호하지 않고 XML 출력 요소로 바인딩할 수 있습니다(즉, JSON에서 XML로 변환). 예를 들어 다음 JSON 문자열이 제공됩니다.

{ "pref1:a": "value1", "pref2:b": "value2" }

Json-lib에 접두사 pref1pref2 를 특정 네임스페이스 URI에 바인딩하도록 pref1:apref2:b 요소에 대한 네임스페이스 선언을 출력하도록 요청할 수 있습니다.

이 기능을 사용하려면 XmlJsonDataFormat.NamespacesPerElementMapping 개체를 만들고 namespaceMappings 옵션(즉, List)에 추가하기만 하면 됩니다.

XmlJsonDataFormat.NamespacesPerElementMapping 에는 요소 이름과 [접두사 네임스페이스 URI의 맵이 있습니다. 여러 접두사 및 네임스페이스 URI를 쉽게 매핑하기 위해 NamespacesPerElementMapping(String 요소, String pipeSeparatedMappings) 생성자는 문자열 기반 파이프-마이크로 구분된 [prefix, namespaceURI] 쌍을 사용합니다. |ns2|http://camel.apache.org/personalData|ns3|http://camel.apache.org/personalData2|.

기본 네임스페이스를 정의하려면 해당 키 필드를 비워 둡니다. |ns1|http://camel.apache.org/test1||http://camel.apache.org/default|.

요소 이름 = 빈 문자열에 바인딩 네임스페이스 선언은 해당 네임스페이스를 root 요소에 연결합니다.

전체 코드는 다음과 같습니다.

XmlJsonDataFormat namespacesFormat = new XmlJsonDataFormat();
List<XmlJsonDataFormat.NamespacesPerElementMapping> namespaces = new ArrayList<XmlJsonDataFormat.NamespacesPerElementMapping>();
namespaces.add(new XmlJsonDataFormat.
                       NamespacesPerElementMapping("", "|ns1|http://camel.apache.org/test1||http://camel.apache.org/default|"));
namespaces.add(new XmlJsonDataFormat.
                       NamespacesPerElementMapping("surname", "|ns2|http://camel.apache.org/personalData|" +
                           "ns3|http://camel.apache.org/personalData2|"));
namespacesFormat.setNamespaceMappings(namespaces);
namespacesFormat.setRootElement("person");

Spring DSL에서 동일한 작업을 수행할 수 있습니다.

372.5.1. 예제

다음 JSON 문자열에서 위의 Java 스니펫의 네임스페이스 바인딩 사용:

{ "name": "Raul", "surname": "Kripalani", "f": true, "g": null}

 

다음과 같은 XML 값을 얻을 수 있습니다.

<person xmlns="http://camel.apache.org/default" xmlns:ns1="http://camel.apache.org/test1">
    <f>true</f>
    <g null="true"/>
    <name>Raul</name>
    <surname xmlns:ns2="http://camel.apache.org/personalData" xmlns:ns3="http://camel.apache.org/personalData2">Kripalani</surname>
</person>

JSON 사양은 다음과 같이 JSON 오브젝트를 정의합니다.

오브젝트는 이름/값 쌍의 순서가 지정되지 않은 세트입니다. […​].

따라서 요소가 출력 XML에서 다른 순서로 표시됩니다.