How to Make GeoServer Return JSON for WMS GetFeatureInfo

geoservergetfeatureinfowms

I wish to get the results of a WMS GetFeatureInfo request as a JSON instead of the table that comes up by default. Out of the box, the only options for the response from a WMS GetFeatureInfo are the table, XML and text.

Best Answer

Update The 'hack' given below is necessary only for Geoserver versions 2.2.x and below. With version 2.3.0 and upwards, Geoserver can return JSON for WMS GetFeatureInfo request natively.

End of Update


There is an open feature request for this on geoserver's bug tracker.

Using custom GetFeatureInfo Templates, it is possible to generate a Json response from Geoserver.

You can follow these steps:

1]Go to the following folder

GEOSERVER_DATA_DIR/workspaces/{workspace}/{datastore}/{featuretype}/

2] Create 3 empty text files with the following names: header.ftl, content.ftl & footer.ftl

3] Open the content.ftl file, and copy the following free-marker code:

[
<#list features as feature>
{ "Type": "${type.name}"
<#list feature.attributes as attribute>
    <#if !attribute.isGeometry>
    , "${attribute.name}": "${attribute.value}"
    </#if>
</#list>
}
</#list> ,{}
]

4] Save the file and now make the WMS getFeatureInfo request. You'll see that the response is in JSON.

Note: You need to remember that this will wrap the numeric values in inverted commas as a string. Hence you might have to take care of it in the client code.