1

一般的なJAXBモデルから、生成されるxmlは次の形式にすることができます

<ipi-list><ipi>1001</ipi><ipi>1002</ipi></ipi-list>

jsonには配列があるため、両方の要素は必要ありません。したがって、MOXyのoxml拡張機能を使用することで、出力をフラット化して次のようにできます。

"ipi" : [ "1001", "1002" ],

しかし、ipiは現在、一連のものを参照しているので、ipiではなくipisと呼びたいと思います。

"ipis" : [ "1001", "1002" ],

MOXyに要素の名前を変更させる方法はありますか?

4

1 に答える 1

1

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" ]
}

詳細については

于 2012-07-12T10:40:05.367 に答える