In Struts 2 example, you will learn how to convert an object into JSON format via “struts2-json-plugin.jar” library.

1. Get dependency library

Get the struts2-json-plugin.jar library.

    <!-- Struts 2 -->

    <!-- Struts 2 JSON Plugins -->

2. Action (JSON)

This is an Action class which will be converted into JSON format.

package com.mkyong.common.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.Action;

public class JSONDataAction{

	private String string1 = "A";
	private String[] stringarray1 = {"A1","B1"};
	private int number1 = 123456789;
	private int[] numberarray1 = {1,2,3,4,5,6,7,8,9};
	private List<String> lists = new ArrayList<String>();
	private Map<String, String> maps = new HashMap<String, String>();
	//no getter method, will not include in the JSON
	private String string2 = "B";
	public JSONDataAction(){
		maps.put("key1", "value1");
		maps.put("key2", "value2");
		maps.put("key3", "value3");
		maps.put("key4", "value4");
		maps.put("key5", "value5");

	public String execute() {
               return Action.SUCCESS;
	public String getString1() {
		return string1;

	public void setString1(String string1) {
		this.string1 = string1;

	public String[] getStringarray1() {
		return stringarray1;

	public void setStringarray1(String[] stringarray1) {
		this.stringarray1 = stringarray1;

	public int getNumber1() {
		return number1;

	public void setNumber1(int number1) {
		this.number1 = number1;

	public int[] getNumberarray1() {
		return numberarray1;

	public void setNumberarray1(int[] numberarray1) {
		this.numberarray1 = numberarray1;

	public List<String> getLists() {
		return lists;

	public void setLists(List<String> lists) {
		this.lists = lists;

	public Map<String, String> getMaps() {
		return maps;

	public void setMaps(Map<String, String> maps) {
		this.maps = maps;

3. struts.xml

To output the JSON data, you need to declared a package which extends the “json-default“, and result type as “json“.

<?xml version="1.0" encoding="UTF-8" ?>
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

   <constant name="struts.devMode" value="true" />
   <package name="default" namespace="/" extends="json-default">
      <action name="getJSONResult" 
       	   <result type="json" />

4. Demo

Access the action URL, the JSONDataAction’s properties will be converted into JSON format.

Struts 2 JSON example

JSON format…

Hope this super simple example can give you an overall idea of how JSON plugin worked with Struts 2. However, there are still many useful settings are not cover here, make sure you read the Struts 2 JSON plugin documentation for more details.

Download Source Code

Download It –


  1. Struts 2 JSON plugin
  2. JSON official documentation