14

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.

user962206
  • 15,637
  • 61
  • 177
  • 270
  • 2
    Have a look at this post http://www.mkyong.com/struts2/struts-2-and-json-example/ – shazin Jan 30 '13 at 08:02
  • ^ That have not worked for me. – user962206 Jan 30 '13 at 08:07
  • It works so try again. It is just telling you to add struts2-json-plugin and use the json result type. – Quaternion Jan 30 '13 at 08:13
  • 1
    It converts the whole action class as JSON. I only want the String to be responded and that example gives me a lot of exceptions. – user962206 Jan 30 '13 at 08:17
  • 1
    To address your update, it is in json format because you manually put it that way. Just use the plugin. If you want slighly more work to do what you want then use a stream result... you can also use a JSP to output JSON see: http://stackoverflow.com/questions/9124960/how-to-simply-return-json-from-a-jsp but really... just use the plugin. – Quaternion Jan 30 '13 at 08:19
  • I am already using the plugin but it is returning a lot of errors. I guess I'll just post that in another question. – user962206 Jan 30 '13 at 08:21
  • 1
    I have the same problem. Struts 2 returns a whole action class with even request params! – emeraldhieu May 27 '13 at 03:20
  • **For those visiting in the future:** it makes little sense to pre-convert the data to a JSON string; instead use the built-in S2 JSON response mechanisms. Simply expose the data you want returned and the framework handles the rest. – Dave Newton May 22 '20 at 20:24

4 Answers4

24

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

Platon
  • 1,513
  • 13
  • 12
  • This looks like the best answer. It worked fine for me. Specially now that json-plugin has been absorbed by Struts2 as a default library. – Felipe Leão Jun 20 '14 at 17:50
  • this does not seem to work using struts 2.5 and the json result. Had exact same setup with another library returning a json string and trying to send it back using json result. I get net.sf.json.JSONException: java.lang.reflect.InvocationTargetException when pointing it at a String property – Paul Zepernick Sep 19 '16 at 19:43
  • 1
    Beware this answer: You should NEVER have instance fields in singletons that you expect to be request-dependent. This is a nasty race condition waiting to happen. – Tyler Hoppe Jun 14 '17 at 21:22
  • @TylerHoppe There is no singleton here I can see--can you explain? **Note to future readers:** this warning is not relevant for normal S2 applications; there is no singleton here, and this answer is perfectly ok (delta it's doing work S2 can already do for you, which doesn't make much sense). – Dave Newton May 22 '20 at 20:24
17

Try using the response's PrintWriter.

Java

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

      response.setContentType("application/json");
      response.getWriter().write(jsonString );

      return null;
   }
Tomas Santos
  • 560
  • 4
  • 12
  • 1
    This is the most correct answer here given that he already has a JSON string. A better approach would be to create an actual `Result` to handle dealing with the `HttpServletResponse`, though. – Steven Benitez Sep 04 '13 at 03:09
2

In Action class put below code.

  public class Struts2Action extends ActionSupport
  {     

    public String jsonString="";

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

      return "success";
   }
  }

In JSP put below code

<%@ taglib prefix="s" uri="/struts-tags" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Struts Rais</title>

<s:property value="jsonString"/><br />

This will print JSON data if you want to manipulate JSON data you cat the data in var <s:set> tag and access the variable in entire page.

1

To return a JSON response you need to include the struts2-json-plugin-2.x.x.jar file in your project build path You will need to set package extends="json-default" result type is json.

struts2-json-plugin-2.x.x.jar file allows you to serialize the Action class attribute which has setters into a JSON object.

Get the jar dependencies from maven

  <dependencies>
<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-core</artifactId>
    <version>2.1.8</version>
</dependency>
<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-json-plugin</artifactId>
    <version>2.1.8</version>
</dependency>

You can get the complete help from this link...

Struts 2 and JSON response