2012-07-12 57 views
1

從生成的XML的形式可以是生成json時,我可以讓MOXy重命名一個元素嗎?

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

常見的JAXB模型,因爲在JSON我們有數組我們不需要這兩種元素,所以通過使用莫西的OXML擴展我可以拼合輸出給

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

但由於IPI現指事物的數組,我想它被稱爲IPIS沒有IPI

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

有沒有辦法讓MOXY重命名一個元素?

回答

1

您可以使用EclipseLink JAXB (MOXy)的外部映射文檔來調整XML或JSON表示的映射。

IPIList

下面是一個域類與JAXB批註XML表示從你的問題相符:

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

我們可以用莫西的外部映射文檔來修改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

要指定莫西爲您的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" ] 
} 

更多信息

+1

好極了,懂了工作按建議。 – 2012-07-12 10:56:52

相關問題