Reputation: 489
I am trying to build a JAX-RS rest api that accepts in the POST method a (JSON) UnMarshelled class and at the moment i am only returning the same class (marshelled back as a JSON).
When I return the object i am getting a plain { } in the browser(postman client). I am using the data provided in this question:.
Is my understanding correct that the same JSON that i am sending should come back as it is ?, if yes not sure why is only { } being received or have i completely missed something.
Below is my code :
@Path("/metadata") public class MetadataResource {
//Anil: This is the method that will be called when a post at /metadata comes
@Consumes(MediaType.APPLICATION_JSON)
@POST
@Produces(MediaType.APPLICATION_JSON)
public ObjectA CreateMetadata_JSON(ObjectA metadata) {
return metadata;
}
Class Object A:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "objectA")
public class ObjectA {
@XmlElement(required = true)
protected String propertyOne;
@XmlElement(required = true)
protected String propertyTwo;
@XmlElement(required = true)
protected ObjectB objectB;
}
and Class Object B:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "objectB")
public class ObjectB {
@XmlElement(required = true)
protected String propertyA;
@XmlElement(required = true)
protected boolean propertyB;
}
The json object being sent is :
{
"objectA" :
{
"propertyOne" : "some val",
"propertyTwo" : "some other val",
"objectB" :
{
"propertyA" : "some val",
"propertyB" : "true"
}
}
}
Upvotes: 0
Views: 113
Reputation: 208994
It's because of the root object wrapper
{
"objectA" :
}
Generally the expected JSON object is everything you have, excluding the above root value wrapper. If there is a requirement to use the JSON exactly how you have it, then the JSON provider needs to be configured to un-wrap the root value. If you don't, then the provider doesn't recognize any properties in the JSON, and you are left with an object with a bunch of nulls. So when you serialize the same object, the provider ignores the null, and you are left with an empty JSON object { }
.
So the simple solution is to just use
{
"propertyOne" : "some val",
"propertyTwo" : "some other val",
"objectB" :
{
"propertyA" : "some val",
"propertyB" : "true"
}
}
If you require the root value wrapper, then I would need to know what JSON provider you are using, before I can try and help with how you can configure it to unwrap the root value.
For MOXy, if you want to configure it to wrap/unwrap the root value, you can setIncludeRoot
to true, in the MoxyJsonConfig
. You will need to provide a ContextResolver
for it to be discovered.
@Provider
public class MoxyConfigResolver implements ContextResolver<MoxyJsonConfig> {
private final MoxyJsonConfig config;
public MoxyConfigResolver() {
config = new MoxyJsonConfig();
config.setIncludeRoot(true);
}
@Override
public MoxyJsonConfig getContext(Class<?> type) {
return config;
}
}
Upvotes: 1