4

I'm using RESTEasy to return Java objects as JSON objects (which is using Jettison Mapped Convention for JSON marshelling).

But I don't want it to return the root node.

For example

@XmlRootElement
public class Car{
    private Integer id;
    private String name;
}

An object of this class would result in JSON:

{"Car":{"id":6,"name":"someName"}}

Because it's actually coming from

<Car>
    <id>6</id>
    <name>someName</name>
</Car>

But I don't want the root node. I just want:

{"id":6,"name":"someName"}

So I can use it with client libraries likes Backbone.js

Is there any way (some annotation) to force this on the JSON marshelling ?

Sam,

Sam
  • 5,375
  • 2
  • 45
  • 54

3 Answers3

3

I was faced with the exact same problem. After doing some research I found people suggested using resteasy-jackson-provider instead of jettison. It was claimed that jettison has a few issues and that what you're experiencing is one of them. I switched to Jackson and found that it solved this issue and probably a few others that I wasn't aware of. If you're using maven:

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jackson-provider</artifactId>
    <version>2.1.0.GA</version>
</dependency>

If you do this, you may see some collisions between jettison. To avoid those make sure you don't have the jettison jars on your classpath.

Enrico
  • 621
  • 1
  • 4
  • 12
1

You can define you Backbone.Mode like this:

var Car = Backbone.Model.extend({
    defaults: function() {
        return {Car: {id: 0, name: 'bar'}};
    }
}
Jian Lyu
  • 11
  • 3
1

I found a jettison related solution on the answer "JAX-RS - JSON without root node in apache CXF".

Jettison has a parameter called dropRootElement that does what the name says. In my case, the following addition of a Configuration-object did the job:

Configuration configuration = new Configuration();
configuration.setDropRootElement(true);

new JettisonMappedXmlDriver(configuration)
    .createWriter(this.getOutputStream()));

Hope it helps...

Community
  • 1
  • 1
L-Ray
  • 1,637
  • 1
  • 16
  • 29