DeepNightTwo
DeepNightTwo

Reputation: 4961

Jersey failed with request header application/xml

I'm new to jersey. I've a test rest for return a Map.

    @GET
    @Path("/maptest")
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public Map<String, TestObject> mapTest()
            throws JdException {
        // return a non-empty HashMap contains String-TestObject
    }

}

It works fine if request head is set to / or application/json. But failed with exception if request head is application/xml:

Caused by: com.sun.jersey.api.MessageException: A message body writer for Java class java.util.HashMap, and Java type java.util.Map<java.lang.String, TestObject>, and MIME media type application/xml was not found
    ... 31 more

I've added XmlRootElement annotation to TestObject. It works with application/xml if return type is set to List<TestObject>. Can't XML handle Map?

Upvotes: 0

Views: 1740

Answers (1)

futuretelematics
futuretelematics

Reputation: 1495

Jersey DOES NOT provide a MessageBodyWriter for Maps, so you cannot return a Map; on the contrary, Jersey DOES provide a MessageBodyWriter for Collections, and that's why it works for Collections

Fortunately you have some options:

  1. Write a custom MessageBodyWriter (see this)
  2. Return a custom object wrapping your map and make it xml-serializable by jaxb; you'll have to write a XmlMapAdapter (see this or this)

Upvotes: 1

Related Questions