您可以使用EclipseLink JAXB(MOXy)的外部映射文档来调整XML或JSON表示形式的映射。
知识产权主义者
下面是带有JAXB批注的域类,该类与您问题中的XML表示相匹配:
package forum11449219;
import java.util.*;
import javax.xml.bind.annotation.*;
@XmlRootElement(name="ipi-list")
public class IPIList {
private List list = new ArrayList();
@XmlElement(name="ipi")
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
}
oxm.xml
我们可以使用MOXy的外部映射文档来修改list属性如何映射到JSON。
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="forum11449219">
jaxb.properties
要将MOXy指定为JAXB提供程序,您需要在与域模型相同的包中包含一个名为jaxb.properties的文件,并带有以下条目(请参阅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 properties = new HashMap(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);
}
}
输出量
这是运行演示代码的输出:
1001
1002
{
"ipis" : [ "1001", "1002" ]
}
欲获得更多信息