JAX-RS, Map <String, String> to JSON without overhead?

I use JAX-RS to create cool Java web services. I get a lot of overhead in the generated JSON.

Data class:

@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Test { private Map<String,String> data; Test() {} public Test(Map<String,String> data) { this.data = data; } public Map<String, String> getData() { return data; } } 

Services:

 @GET @Path("/test") @Produces("application/json; charset=UTF-8;") public Test test() { Map<String,String> map = new HashMap<String,String>(); map.put("foo", "bar"); map.put("bingo", "bongo"); return new Test(map); } 

It produces:

 {"data":{"entry":[{"key":"foo","value":"bar"},{"key":"bingo","value":"bongo"}]}} 

I would like it to produce:

 {"data":{"foo":"bar","bingo":"bongo"}} 

What is the easiest way to achieve this? I can change my data class, but I cannot know the keys or the size of the map in advance.

+7
java json rest map jax-rs
source share
3 answers

The simplest way would be to use List<Pair> instead of Pair , where Pair is just javabed with two properties.

+5
source share

The JAXB specification defines special handling for Map when it is used as a bean property.

In light of this, I don’t think you can do much (for now), except perhaps for writing your own MessageBodyWriter ( https://jsr311.dev.java.net/nonav/javadoc/javax/ws/rs /ext/MessageBodyWriter.html )

+1
source share

If you are not using JAXB annotated objects, but just POJOs, you can get the right behavior by simply enabling the POJO mapping function along with the Jackson JSON library.

So, in web.xml , if you use a filter (similar to a servlet), your configuration should be:

 <filter> <filter-name>Jersey</filter-name> <filter-class>...</filter-class> <init-param> <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> <param-value>true</param-value> </init-param> </filter> 

And just depend on the jersey-json dependency in your maven configuration, or download it from a website and put jackson in your classpath. See Also this answer and this answer , and this blog post . And why on earth is this not standard behavior that I don’t know about.

+1
source share

All Articles