Saturday, 18 February 2012

Wrapping and Unwrapping JSON response in CXF

Q. How to drop root element in the JSON response?
A. You need to set the JSONProvider's dropRootName property to true. Here is a sample cxf config for this:

<jaxrs:server id="${}" address="/">
	<ref bean="${service.ref}" />
	<bean class="org.apache.cxf.jaxrs.provider.JSONProvider">
	<property name="dropRootName" value="true"></property>
	<entry key="json" value="application/json" />
Q. How to wrap the JSON response with a name?
A. You need to set the JSONProvider's supportUnwrapped property to true and also set the wrapperName for the root element (If you have more than one wrapperName then use wrapperMap property). Here is a sample cxf config for this:

<jaxrs:client id="${}" 
	<entry key="Content-Type" value="application/json" />
	<bean class="org.apache.cxf.jaxrs.provider.JSONProvider">
	<property name="supportUnwrapped" value="true"></property>
	<property name="wrapperName" value="${}"></property>
In case you are intersted in knowing how JSONProvider uses the wrapperName mentioned above while reading the JSON data, here is the code-snippet:

protected String getRootName(Class cls, Type type) throws Exception {
	String name = null;
	if (wrapperName != null) {
	name = wrapperName;
	} else if (wrapperMap != null) {
	name = wrapperMap.get(cls.getName());
	if (name == null) {
	QName qname = getQName(cls, type, null, false);
	if (qname != null) {
	name = qname.getLocalPart();
	String prefix = qname.getPrefix();
	if (prefix.length() > 0) {
	name = prefix + "." + name;
	if (name == null) {
	throw new WebApplicationException(500);
	return "{\"" + name + "\":";

1 comment:

  1. It appears that property "dropRootName" has been remamed as "dropRootElement" in JSONProvider. But it works the same