2011-04-01 77 views
2

我在我的RESTEasy項目中使用EclipseLink的MOXy作爲JAXB實現.MOXy的高級功能已經通過@XmlDiscriminatorNode &這樣的註釋帶來了很多幫助。除了一件事情之外,一切工作都很好:JSON支持。我使用RESTEasy的JettisonMappedContext,但不幸的是,在編組後,只有實例變量字段屬於我的JSON中的抽象超類。MOXy JSON支持

@XmlRootElement 
@XmlDiscriminatorNode("@type") 
public abstract class Entity { 

    public Entity(){} 

    public Entity(String id){ 
     this.id = id; 
    } 

    private String id; 

    @XmlElement 
    public String getId() { 
     return id; 
    } 
    public void setId(String id) { 
     this.id = id; 
    } 
} 

子類:

編組後
<object type="photo"> 
    <id>photoId423423</id> 
    <thumbnail>http://dsadasadas.dsadas</thumbnail> 
</object> 

JSON:

"object":{"id":"photoId423423"} 

是否有任何其他的方式來實現這一目標編組後

@XmlRootElement 
@XmlDiscriminatorValue("photo") 
public class Photo extends Entity{ 

    private String thumbnail; 

    public Photo(){} 

    public Photo(String id) { 
     super(id); 
    } 

    public void setThumbnail(String thumbnail) { 
     this.thumbnail = thumbnail; 
    } 

    @XmlElement(name="thumbnail") 
    public String getThumbnail() { 
     return thumbnail; 
    } 
} 

XML?

謝謝。

回答

4

更新2

的EclipseLink 2.4已經發布了莫西的JSON綁定:

更新1

獲取本機的潛行高峯MOXy對象到JS具有約束力的的EclipseLink 2.4添加:


確保您已包含一個文件名爲jaxb.properties與您的模型類文件,其中包含以下條目:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory 

如果沒有此條目,將使用參考實現,並且EclipseLink JAXB (MOXy)擴展名不會出現在結果中g XML/JSON。


使用從我的博客中@DescrimatorNode example,生成的XML將是:

<customer> 
    <contactInfo classifier="address-classifier"> 
     <street>1 A Street</street> 
    </contactInfo> 
</customer> 

當我名帥利用拋棄:

StringWriter strWriter = new StringWriter(); 
MappedNamespaceConvention con = new MappedNamespaceConvention(); 
AbstractXMLStreamWriter w = new MappedXMLStreamWriter(con, strWriter); 
marshaller.marshal(customer, w); 
System.out.println(strWriter.toString()); 

然後我得到以下JSON:

{"customer":{"contactInfo":{"@classifier":"address-classifier","street":"1 A Street"}}} 

有關JAXB和JSON詳細信息請參閱:

+0

非常感謝詳細answer.You又一次救了我:) – barand 2011-04-06 08:51:53