This is about a REST PUT call with a JSON Object whith a root element, let's say, something like :
{"place":
{"name":"Here",
"address":
{"address":"somewhere under the rainbow",
"city":
{"name":"Oz",
"country":
{"name":"Oz",
"zone":"Far Far Away"}
}
}
}
}
defined with Jaxb Annotations
@XmlRootElement
public class PlaceOffline extends GlobalElement {
@XmlElement
public Address address;
}
and the superclass is
@XmlRootElement
public class GlobalElement implements Serializable {
@XmlElement
public Integer id;
@XmlElement
public String name;
@XmlElement
public String uniqueLabel;
}
I wrote a client and It miserabily failed with an
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "placeOffline"
I decide then to log the call and create a ContainerRequestFilter to do this
@Provider
public class RestLogFilter implements ContainerRequestFilter {
private Logger LOGGER_filter = Logger.getLogger(RestLogFilter.class.getName());
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
if (!MediaType.APPLICATION_JSON_TYPE.equals(requestContext.getMediaType())
|| requestContext.getEntityStream() == null) {
return;
}
InputStream inputStream = requestContext.getEntityStream();
byte[] bytes = IOUtils.readFully(inputStream , -1, true);
LOGGER_filter.info("Posted: " + new String(bytes, "UTF-8"));
requestContext.getEntityStream().mark(0);
}
}
And, guess what ?
It worked, unexpectedly ! No more Errors. The printing of the entity solves the problem. Awkward.
I see it like a workaround and it bothers me a little, has anyone an explanation ? A more elegant way to solve this issue ?
I am using WildFly 8.2
EDIT :
It worked with
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper mapper;
public ObjectMapperContextResolver() {
mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
}
@Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
}