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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With