Struts 2 + JSON Integration Annotation Example

By Arvind Rai, January 03, 2015
In this page, we will learn Struts 2 JSON integration using annotation. Struts 2 supports JSON response using JSON plugin. We need to use json-default as parent package. The action method should return result as json type. To achieve it we need to define result type as json. Find the sample example step by step.

Required Software to Run Example

To run the example, we need below software.
1. Java 6
2. Tomcat 7
3. Eclipse
4. Maven

Project Structure in Eclipse

Find the project structure in eclipse for struts 2 and JSON integration.
Struts 2 + JSON Integration Annotation Example

Struts2 JSON Plugin

To resolve the struts 2 JSON API, we need the below plugin in our pom.xml

json-default Parent Package

To support JSON, we need to use json-default in parent package. Use below annotation in the action class.

json Result Type

The return type of action method should be JSON. To achieve it, struts 2 provides json type in result. Define it as below.

Action Class to Return JSON

Now find the action class where we are generating a sample JSON. We can use collection to create the required JSON. To get the output create setter and getter method of the property.
package com.concretepage.action;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import com.opensymphony.xwork2.ActionSupport;
public class Struts2JSON extends ActionSupport{
	private static final long serialVersionUID = 1L;
	private List<String> listOfName = Arrays.asList("Ram","Shyam","Mohan");
	private List<String> listOfCity = Arrays.asList("Varanasi","Jaunpur","Bhadohi");
	private Map<String,List<String>> map =  new HashMap<String,List<String>>();
		map.put("names", listOfName);
		map.put("cities", listOfCity);
	private List<Map<String,List<String>>> result = new ArrayList<Map<String,List<String>>>();
	public String one() {
	    return SUCCESS;
	public List<Map<String, List<String>>> getResult() {
		return result;
	public void setResult(List<Map<String, List<String>>> result) {
		this.result = result;

web.xml for the Application

Find the web.xml for struts 2.
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "" >
  <display-name>Struts 2 JSON </display-name>

Complete pom.xml Used in Example

Find the pom.xml that is being used in example to resolve struts 2 JAR dependency.
<project xmlns="" xmlns:xsi=""


To run the example, create WAR using maven and deploy it into tomcat. Use below URL to run the application. http://localhost:8080/struts2json-1/json
We will get JSON response as
Find the screen shot of the browser.
Struts 2 + JSON Integration Annotation Example
Now we are done. Happy learning.

Download Source Code


©2024 | Privacy Policy | Contact Us