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="${service.name}" address="/">
	<jaxrs:schemaLocations>
	<jaxrs:schemaLocation>classpath:${service.def}.xsd</jaxrs:schemaLocation>
	</jaxrs:schemaLocations>
	<jaxrs:serviceBeans>
	<ref bean="${service.ref}" />
	</jaxrs:serviceBeans>
	<jaxrs:providers>
	<bean class="org.apache.cxf.jaxrs.provider.JSONProvider">
	<property name="dropRootName" value="true"></property>
	</bean>
	</jaxrs:providers>
	<jaxrs:extensionMappings>
	<entry key="json" value="application/json" />
	</jaxrs:extensionMappings>
</jaxrs:server>
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="${service.name}" 
	address="${service.url}" 
	serviceClass="${service.class}"
	inheritHeaders="true">
	<jaxrs:headers>
	<entry key="Content-Type" value="application/json" />
	</jaxrs:headers>
	<jaxrs:providers>
	<bean class="org.apache.cxf.jaxrs.provider.JSONProvider">
	<property name="supportUnwrapped" value="true"></property>
	<property name="wrapperName" value="${response.wrapper.name}"></property>
	</bean>
	</jaxrs:providers>
</jaxrs:client>
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

    ReplyDelete