本文主要是介绍struts2 spring json报JSONException,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
对于spring配置文件中定义的bean,在java代码中含有get方法而且struts中使用了json返回,而这个bean在转json中不用转成json,需要在它的get方法上加@JSON(serialize=false),或者把get方法删除。否则会报org.apache.struts2.json.JSONException。
比如applicationContext.xml中有一个bean中含有jdbcTemplate属性,而example.TestAjax类中转json中不用转jdbcTemplate属性,则要在getJdbcTemplate()方法上加注解@JSON(serialize=false),而属性s在类中不是bean的定义类型,则正常,下面执行结果中返回的object中包含了list和s,虽然s没有特意转成json。返回的object含有类中所有get方法返回的内容。
<bean id="a" class="example.TestAjax"><property name="jdbcTemplate" ref="jdbcTemplate" /><property name="s" value="test"/>
</bean>
example.TestAjax
package example;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import net.sf.json.JSONObject;import org.apache.struts2.json.annotations.JSON;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;import com.opensymphony.xwork2.ActionSupport;public class TestAjax extends ActionSupport{private static final long serialVersionUID = 1L;private String result;private JdbcTemplate jdbcTemplate;private String s;public String getS() {return s;}public void setS(String s) {this.s = s;}public String ajaxMap(){Map<String, String> map = new HashMap<String, String>(); map.put("name", "Name"); JSONObject json = JSONObject.fromObject(map); result = json.toString();return SUCCESS;}public String ajaxList() throws JsonGenerationException, JsonMappingException, IOException{String sql = "select * from user;";final List<User> list = new ArrayList<User>();jdbcTemplate.query(sql, new RowCallbackHandler(){@Overridepublic void processRow(ResultSet arg0) throws SQLException {User u = new User(); u.setName(arg0.getString("User"));u.setPassword(arg0.getString("Password"));list.add(u);}});
// JSONObject obj = JSONObject.fromObject(l);//jacksonObjectMapper o = new ObjectMapper();
// result = o.writeValueAsString(l);result = o.writeValueAsString(list);return SUCCESS;}public String getResult() {return result;}public void setResult(String result) {this.result = result;}// @JSON(serialize=false)不能少,不然返回json时会报错@JSON(serialize=false)public JdbcTemplate getJdbcTemplate() {return jdbcTemplate;}public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {this.jdbcTemplate = jdbcTemplate;}//User要加public不然上面的转json会提示找不到set方法public class User{private String name;private String password;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}
}
控制台输出 Object{ result="[{"name":"root","passwo...FE62151AE967ECA5E0AA"}]",s="test"}
这篇关于struts2 spring json报JSONException的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!