我在 RESTEasy 项目中使用 EclipseLink 的 MOXy 作为 JAXB 实现。@XmlDiscriminatorNode & Value 等注释带来的 MOXy 高级功能对我帮助很大。一切都工作正常,除了一件事:JSON 支持。我正在使用 RESTEasy 的 JettisonMappedContext,但不幸的是,在编码后,我的 JSON 中只有实例变量字段属于抽象父类(super class)。
@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;
}
}
子类:
@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:
<object type="photo">
<id>photoId423423</id>
<thumbnail>http://dsadasadas.dsadas</thumbnail>
</object>
编码后的 JSON:
"object":{"id":"photoId423423"}
还有其他方法可以达到这个目的吗?
谢谢。
最佳答案
更新2
EclipseLink 2.4 已与 MOXy 的 JSON 绑定(bind)一起发布:
更新1
抢先了解 EclipseLink 2.4 中添加的 native MOXy 对象到 JSON 绑定(bind):
确保您已在模型类中包含名为 jaxb.properties 的文件,其中包含以下条目:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
如果没有此条目,将使用引用实现,并且 EclipseLink JAXB (MOXy)扩展名不会出现在生成的 XML/JSON 中。
使用@DescrimatorNode example从我的博客来看,生成的 XML 为:
<customer>
<contactInfo classifier="address-classifier">
<street>1 A Street</street>
</contactInfo>
</customer>
当我利用 Jetison 进行编码时:
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 的更多信息,请参阅:
关于json - MOXy JSON 支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5510697/