将数组从Jquery发送到Struts1方法
我的jsp和jquery代码为
var article = new Object(); article.title = "abc"; article.url = "abc"; article.categories = [1,2,3]; article.tags = [1,2,3]; console.log('hi'); $.ajax({ type: 'POST', url: URL, contentType:"application/json", data: JSON.stringify(article), dataType: 'json', success: function(result) { console.log(result); }, error: function(e){ alert('Error in Processing'); } });
和我的java代码一样
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); String json = ""; if(br != null){ json = br.readLine(); } // 2. initiate jackson mapper ObjectMapper mapper = new ObjectMapper(); //mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); // 3. Convert received JSON to Article Article article = mapper.readValue(json, Article.class);
现在我的Arcticle课程是
public class Article { private String title; private String url; private List categories; private List tags; //getters and setters }
现在我正在排除exception
String json = ""; if(br != null){ json = br.readLine(); }
我得到如下json
{"title":"abc","url":"abc","categories":"[1, 2, 3]","tags":"[1, 2, 3]"}
实际上它应该是
{"title":"abc","url":"abc","categories":[1, 2, 3],"tags":[1, 2, 3]}
我不明白发生了什么,因此我得到exception,因为com.fasterxml.jackson.databind.JsonMappingException:无法在[来源:java.io.StringReader@f94ca;来自VALUE_STRING标记的反序列化java.util.ArrayList的实例。 line:1,column:27](通过参考链:com.ihexa.common.admin.cabsharing.action.Article [“categories”])
我按照以下方式解决了答案
文章user = mapper.readValue(point,Article.class);
的System.out.println(user.getRouteFirst());
Gson gson = new Gson();
TypeToken> token = new TypeToken>(){}; 列出personList = gson.fromJson(user.getRouteFirst(),token.getType());
文章类为
公共类别文章{
private String routeFirst; private String routeSecond;
//塞特犬和吸气剂
}
jsp jquery代码为
var article = new Object(); article.routeFirst = newRoute1; article.routeSecond = newRoute2; $.ajax({ type: 'POST', url: '../..//admin/cabsharing/findIntersesctionPoint.do', data : "point="+JSON.stringify(article), dataType: 'json', success: function(result) { console.log("success"); }, error: function(e){ console.log("error"); } });
我的jsp
会,
Calculator
我的servlet
将是,
public class JsonServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String point = request.getParameter("point"); System.out.println("Point : " + point ); if(point != null){ ObjectMapper mapper = new ObjectMapper(); try { // read from string, convert it to Article class object Article user = mapper.readValue(point, Article.class); // Conver the Article class object in to the JSON string System.out.println("Output Json String is :::::::::::> "+mapper.writeValueAsString(user)); } catch (Exception e) { e.printStackTrace(); } } } }
这是我在控制台中得到的output
,
Point : {"title":"abc","url":"abc","categories":[1,2,3],"tags":[1,2,3]} Json String is :::::::::::> {"title":"abc","url":"abc","categories":["1","2","3"],"tags":["1","2","3"]}
希望这可以帮助。