RESTEasy / Jettison, return Java object as JSON without node root

I use RESTEasy to return Java objects as JSON objects (which use the Jettison Mapped protocol for JSON marshelling).

But I do not want it to return the root of the node.

for instance

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

An object of this class will result in JSON:

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

Because it really comes from

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

But I do not want root node. I just want to:

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

So that I can use it with client libraries like Backbone.js

Is there any way (some kind of annotation) to force this on JSON Marshalling?

Sam,

+4
source share
3 answers

I ran into the same problem. After some research, I found that people suggested using resteasy-jackson-provider instead of dropping. It has been argued that dropping has several problems and that what you are experiencing is one of them. I switched to Jackson and found that he had solved this problem and possibly a few others that I did not know about. If you are 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 can see some collisions between the release. To avoid this, make sure you don't have discard banners on the way to the class.

+3
source

You can define Backbone.Mode as follows:

 var Car = Backbone.Model.extend({ defaults: function() { return {Car: {id: 0, name: 'bar'}}; } } 
+1
source

I found a throwback solution to the answer "JAX-RS - JSON without root node in apache CXF" .

Jettison has a parameter called dropRootElement that does what that name says. In my case, the following addition to the Configuration object completed the task:

 Configuration configuration = new Configuration(); configuration.setDropRootElement(true); new JettisonMappedXmlDriver(configuration) .createWriter(this.getOutputStream())); 

Hope this helps ...

+1
source

Source: https://habr.com/ru/post/1382470/


All Articles