Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAX-RS JAXB Jackson not using @XmlRootElement name

I am developing a restful application with JAX-RS and JAXB. I want to send following Entity as JSON to my client:

@XmlRootElement(name = "user")
@XmlAccessorType(XmlAccessType.FIELD)
public class UserDTO implements Serializable
{
    private static final long serialVersionUID = 1L;

    private Long id;
    private String username;
    private String firstname;
    private String lastname;

    // getter & setter
}

The method in my WebService is defined as follows:

@POST
@Path("users/{id}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public UserAccountDTO login(@PathParam("id") Long id)
{
    UserAccountDTO userAccount = loadUserAccount(id);
    return userAccount;
}

First problem was, that the root node was not send via JSON. Therefore I have added following Class:

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class SkedFlexContextResolver implements ContextResolver<ObjectMapper>
{
    private ObjectMapper objectMapper;

    public SkedFlexContextResolver() throws Exception
    {
        this.objectMapper = new ObjectMapper().configure(SerializationFeature.WRAP_ROOT_VALUE, true);
    }

    @Override
    public ObjectMapper getContext(Class<?> objectType)
    {
        return objectMapper;
    }
}

Now, the root node is send with the data. In case of XML everything is fine (root node is equal to name of @XmlRootElement). See following XML response:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user>
  <id>10</id>
  <username>Admin</username>
  <firstname>Administrator</firstname>
</user>

But in case of JSON the root node is the Classname of the POJO:

{
    "UserAccountDTO":
    {
        "id": 10,
        "username": "Admin",
        "firstname": "Administrator",
        "lastname": null
    }
}

Why differs the output between XML and JSON? What do I need to change to get the specified name in the @XmlRootElement-Annotation

like image 458
Georg Leber Avatar asked Jul 22 '15 16:07

Georg Leber


1 Answers

I had to register Jaxb module to the xml mapper like this, otherwise the @XmlRootElement(name = "myname") was igonerd.

JaxbAnnotationModule module = new JaxbAnnotationModule();
xmlMapper.registerModule(module);
like image 113
Baked Inhalf Avatar answered Sep 28 '22 04:09

Baked Inhalf