我正在使用RESTEasy将Java对象作为JSON对象返回(使用Jettison Mapped Convention进行JSON marshelling)。
但我不希望它返回根节点。
例如
@XmlRootElement
public class Car{
private Integer id;
private String name;
}
此类的对象将导致JSON:
{"Car":{"id":6,"name":"someName"}}
因为它实际上来自
<Car>
<id>6</id>
<name>someName</name>
</Car>
但我不想要根节点。我只想要:
{"id":6,"name":"someName"}
所以我可以将它用于客户端库,如Backbone.js
是否有任何方法(某些注释)强制执行JSON marshelling?
山姆,
答案 0 :(得分:3)
我遇到了完全相同的问题。在做了一些研究后,我发现人们建议使用resteasy-jackson-provider而不是jettison。 有人声称放弃有一些问题,而你所经历的就是其中之一。我切换到杰克逊,发现它解决了这个问题,可能还有一些我不知道的问题。 如果你正在使用maven:
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>2.1.0.GA</version>
</dependency>
如果你这样做,你可能会看到jettison之间的一些碰撞。为了避免这些,请确保您的类路径上没有抛弃罐。
答案 1 :(得分:1)
您可以像这样定义Backbone.Mode:
var Car = Backbone.Model.extend({
defaults: function() {
return {Car: {id: 0, name: 'bar'}};
}
}
答案 2 :(得分:1)
我在答案"JAX-RS - JSON without root node in apache CXF"上找到了与放弃相关的解决方案。
Jettison有一个名为dropRootElement
的参数,可以完成名称所说的内容。在我的例子中,以下添加Configuration
- 对象完成了这项工作:
Configuration configuration = new Configuration();
configuration.setDropRootElement(true);
new JettisonMappedXmlDriver(configuration)
.createWriter(this.getOutputStream()));
希望它有所帮助...