Struts 2 and JSON example
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.
pom.xml
<!-- Struts 2 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.1.8</version> </dependency> <!-- Struts 2 JSON Plugins --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-json-plugin</artifactId> <version>2.1.8</version> </dependency>
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(){ lists.add("list1"); lists.add("list2"); lists.add("list3"); lists.add("list4"); lists.add("list5"); 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" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="json-default"> <action name="getJSONResult" class="com.mkyong.common.action.JSONDataAction"> <result type="json" /> </action> </package> </struts>
4. Demo
Access the action URL, the JSONDataAction’s properties will be converted into JSON format.
http://localhost:8080/Struts2Example/getJSONResult.action

JSON format…
{
"lists":["list1","list2","list3","list4","list5"],
"maps":
{
"key4":"value4","key3":"value3","key5":"value5","key2":"value2","key1":"value1"
},
"number1":123456789,
"numberarray1":[1,2,3,4,5,6,7,8,9],
"string1":"A",
"stringarray1":["A1","B1"]
}





Hi,
I’m facing this exception
org.apache.struts2.json.JSONException: java.lang.reflect.InvocationTargetException at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:243)
what can be the root cause for this..?
hi my problem is , i have 2 autocomplet , i generte the autcolmplet via json into my actions , i use tiles for disply my pages web, every thnk it s ok when i dsplu one eutocomplet in the page, bu when i disply 2 autocolpete int same page nothhing happen int the autocolmplet ???
Hi mkyong,
Can you please help me? After getting the JSON output/data, how can I manipulate it(e.g. display it on my HTML page, pass the JSON data to a javascript/jquery variable, etc.)? Thanks!
Hello i am try to run my first JSON with struts but i am facing one problem, whenever i am try to execute my program on browser url ex: http://localhost:8080/getJSONDATAResult after pressing enter i am getting one popup to save or open dialog.so please do help me in this matter.
can we limiting the variable which should displaying? Because, if i put 3 variables with getter of it, all of it will be displaying/passing. whereas, i just want to display one variable
Thank you Mkyong
Hey guys,
I have a problem with struts2 and json configuration, i hope you can help me… As it didn’t work at my application i tried this example but i’ve got the same results.
The request is sent, and json is generated well. The only problem i have is, that the json string returns as a file. So when i call the getJSONResult action it will give me a file with the json string in it, which i can open or download…
I tried out to set a mine-type in tomcats web.xml:
json application/jsonSame effects…
So i think it’s a configuration problem, but i can’t find it. I would be very glad if somebody could help me, thanks guys!
Do you have ZIP archive of this project ready to import into Eclipse as a dynamic web project?
We’re an Ant shop, we don’t know Maven and I get it working in Eclipse.
Thank you!
Hi. Thanks for your post, I have a cuestion, when I put in my package (inside the struts.xml) this ‘extend=”hibernate-default, json-default”‘ my sessionTarget return me NULL, how I can do for that work?
did you include the struts2-json-plugin.jar dependency?
yes, inside the pom.xml. like this:
org.apache.struts
struts2-json-plugin
2.2.1.1
com.google.code
struts2-fullhibernatecore-plugin
2.2.1
Download this project and run to verify if this project working?
Then compare with yours to spot the different.
Hi, thanks for your answers. yes, this example is runing. aaamm When i delete the “json-default” the sessionTarget is working, and when I delete the “hibernate-default” the json too working, but when I put the two is not working, why?
Hi, I change the order for this
extends = “json-default, hibernate-default”
and apparently is working!
do you think that is the problem?
Hi,
When I run this web application I got :
There is no Action mapped for namespace / and action name . – [unknown location]
com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:178)
org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61)
org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:47)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:478)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:861)
org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1584)
java.lang.Thread.run(Thread.java:619)
Can you please help me.
Thanks
Turn on your debug mode, n double confirm your typo error.
http://www.mkyong.com/struts2/there-is-no-action-mapped-for-namespace-and-action-name-youractionname/
My friend Mkyoung,
I changed the devMode from true to false, but still nothing, did you notice that in the output of the error there is no name of the action, there is only a dot (.) :
HTTP Status 404 – There is no Action mapped for namespace / and action name .
type Status report
message There is no Action mapped for namespace / and action name .
description The requested resource (There is no Action mapped for namespace / and action name .) is not available.
Apache Tomcat/6.0.28
Thanks, your help is appreciated
then, Zip your project and send to me.
how did you fix this. i have the same problem. thanks!
I am seeing the action being called twice,
I see in your example, most of your business logic resides in your constructor
and:
public String execute() {
return Action.SUCCESS;
}
and method execute is being empty, if you experiment, the execute method will be called twice, Do you you know wny ?
Thanks
where can i download the file?
hi
i am generating json by the above method and i am using jquery to retrieve the json data
everything is working fine the only problem is that execute function is getting called twice. Is this a bug or something ?
did you figure this one yet? why it is called twice?
Thanks
My Action class has references to other class (which also implements serializable). i am getting the below. error .. any ideas?
org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: java.lang.reflect.InvocationTargetException
org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:243) org.apache.struts2.json.JSONWriter.process(JSONWriter.java:165) org.apache.struts2.json.JSONWriter.value(JSONWriter.java:131) org.apache.struts2.json.JSONWriter.write(JSONWriter.java:99) org.apache.struts2.json.JSONUtil.serialize(JSONUtil.java:112) org.apache.struts2.json.JSONResult.execute(JSONResult.java:198) com…hony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:190) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:485) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
when you are viewing Java error messages, you should focus on the “caused by” error message.
Please paste your “caused by” error message.
I dont have any “caused by”
just Messages::
weird case, Positioned Update not supported? Mind to send me your source code?
how can i skip particular variable from action, not to be serialize in json object?
To mark an instance variable as not for serialization, you add the transient keyword to the definition.
See http://java.sun.com/developer/technicalArticles/ALT/serialization/
Thanks for the post. It was helpful for me.