JSON Result

Last modified by Ken McWilliams on 2012/03/21 23:41

Java Script Object Notation (JSON) is a very easy to consume format that lets us easily use AJAX inside our pages.  By using AJAX in our applications we can make our actions smaller as they can now marshal less resources.  This is because pages will now make requests of several actions to get the data they need.  We are lucky that creating JSON in Struts2 is very easy.

We can follow these instructions easily with an existing Struts2 project but if you have yet to create one start here.

For the following example we will also use the conventions plugin, for an explaination of the plugin see here.

1) Add the struts2-json-plugin-VERSION.jar (where VERSION is the same as struts2-core-VERSION.jar) to your class path.

2 a) Create an action with the required getters which will return the data as JSON. The JSON plugin only serializes getters and not public attributes.

2 b) Declare the action as being in the json-default package.

2 c) Declare the action as having a json result.

As an example lets only return a Greeting message containing: Hello, World!

package com.kenmcwilliams.action.json;
import com.opensymphony.xwork2.ActionSupport;

@ParentPackage("json-default")
@Result(type = "json")
public class HelloWorld extends ActionSupport{
    private String greeting = "Hello, World!";
    public String getGreeting(){
        return greeting;
    }
}

Result: When we goto CONTEXT_ROOT/json/hello-world we will see the following (if using firefox which is kind enough to show JSON)

{"greeting":"Hello, World!"} 

Explaination: To understand where json-default and the json result types come from, expand the struts2-json-plugin-VERSION.jar, in the default package open struts-plugin.xml.  This file is present in all plugins and is processed before the framework starts up and adds namespaces, packages, results types... anything you can add your self in struts.xml.