Struts2 How to Return a JSON Response

user962206 picture user962206 · Jan 30, 2013 · Viewed 48.4k times · Source

I am currently creating a web-application where the users can fetch tags from the database as JSON,

here is my struts action

public String execute(){


    Gson gson = new Gson();
    String tagsAsJson = gson.toJson(audioTaggingService.findTagsByName(q));
    System.out.println(tagsAsJson);

    return "success";
}

UPDATE:

The tagsAsJson is already in a JSON format all I want is to return only that, and not the whole class action itself.

It returns something like this

This is the data I want to return to the user

[{"id":2,"name":"Dubstep","description":"Dub wob wob"},{"id":3,"name":"BoysIIMen","description":"A 1990s Boy Band"},{"id":4,"name":"Sylenth1","description":"A VST Plugin for FLStudio "}]

How do I return the tagsAsJson as a r JSON esponse? since that JSON response will be used by the client side code.

Answer

Platon picture Platon · Sep 3, 2013

Use the Struts "JSON Plugin".

Quite easy, three steps:

Just include it in your maven project like this

<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-json-plugin</artifactId>
    <version>${version.struts2}</version>
</dependency>

Declare the field you'd like to return as JSON string like the field of your action, provide the getter and setter.

public class Struts2Action extends ActionSupport {

    private String jsonString;

    public String execute() {
        Gson gson = new Gson();
        jsonString = gson.toJson(audioTaggingService.findTagsByName(q));

        return "success";
    }

    public String getJsonString() {
        return jsonString;
    }

    public void setJsonString(String jsonString) {
        this.jsonString = jsonString;
    }
}

And, finally, put this in your XML:

<action name="someJsonAction" class="com.something.Struts2Action">
    <result type="json">
        <param name="noCache">true</param>
        <param name="excludeNullProperties">true</param>
        <param name="root">jsonString</param>
    </result>
</action>

Pay attention to <param name="root">jsonString</param>. This piece of xml tells Struts2 that this exact property should be considered as a root for JSON serialization. So only the named property (and below, if it's a map or whatsoever) will be returned in a JSON response.

Thanks to the JSON Plugin the content type will be correct.

"JSON Plugin" documentation is here: http://struts.apache.org/release/2.3.x/docs/json-plugin.html