EclipseLink JAXB(MOXy)の外部マッピングドキュメントを使用して、XMLまたはJSON表現のマッピングを微調整できます。
IPIList
以下は、質問のXML表現と一致するJAXBアノテーションを持つドメインクラスです。
package forum11449219;
import java.util.*;
import javax.xml.bind.annotation.*;
@XmlRootElement(name="ipi-list")
public class IPIList {
private List<String> list = new ArrayList<String>();
@XmlElement(name="ipi")
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
}
oxm.xml
MOXyの外部マッピングドキュメントを使用して、list
プロパティがJSONにマッピングされる方法を変更できます。
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="forum11449219">
<java-types>
<java-type name="IPIList">
<java-attributes>
<xml-element java-attribute="list" name="ipis"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
jaxb.properties
MOXyをJAXBプロバイダーとして指定するには、jaxb.properties
ドメインモデルと同じパッケージで呼び出されるファイルを次のエントリに含める必要があります(を参照)。
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
デモ
次のデモコードは、を作成するときに外部マッピングドキュメントを参照する方法を示していますJAXBContext
。
package forum11449219;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
IPIList ipiList = new IPIList();
ipiList.getList().add("1001");
ipiList.getList().add("1002");
// XML
JAXBContext jc = JAXBContext.newInstance(IPIList.class);
Marshaller xmkMarshaller = jc.createMarshaller();
xmkMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
xmkMarshaller.marshal(ipiList, System.out);
// JSON
Map<String, Object> properties = new HashMap<String, Object>(3);
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "forum11449219/oxm.xml");
properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
JAXBContext jsonJC = JAXBContext.newInstance(new Class[] {IPIList.class}, properties);
Marshaller jsonMarshaller = jsonJC.createMarshaller();
jsonMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jsonMarshaller.marshal(ipiList, System.out);
}
}
出力
デモコードの実行からの出力は次のとおりです。
<?xml version="1.0" encoding="UTF-8"?>
<ipi-list>
<ipi>1001</ipi>
<ipi>1002</ipi>
</ipi-list>
{
"ipis" : [ "1001", "1002" ]
}
詳細については