从Jquery发送数组到Struts1方法 [英] sending array from Jquery to Struts1 method

查看:73
本文介绍了从Jquery发送数组到Struts1方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的jsp和jquery代码为

My jsp and jquery code as

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课是

Now My Arcticle class is

public class Article {

    private String title;
    private String url;
    private List<String> categories;
    private List<String> tags;

//getters and setters
}

现在我正在将异常排除在外 在第

Now I am geeting exception as at line

String json = "";
                if(br != null){
                    json = br.readLine();
                }

我按如下方式获取json

i get json as follows

{"title":"abc","url":"abc","categories":"[1, 2, 3]","tags":"[1, 2, 3]"}

实际上应该是

{"title":"abc","url":"abc","categories":[1, 2, 3],"tags":[1, 2, 3]}

我不明白发生了什么事 因此我得到了例外 com.fasterxml.jackson.databind.JsonMappingException:无法反序列化VALUE_STRING令牌中的java.util.ArrayList实例 在[来源:java.io.StringReader@f94ca;第1行,第27列](通过参考链:com.ihexa.common.admin.cabsharing.action.Article ["categories"])

I dont understand whts happening and hence i get exception as com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token at [Source: java.io.StringReader@f94ca; line: 1, column: 27] (through reference chain: com.ihexa.common.admin.cabsharing.action.Article["categories"])

我通过以下方式解决了答案

I solved the answer in following way

文章用户= mapper.readValue(point,Article.class);

Article user = mapper.readValue(point, Article.class);

System.out.println(user.getRouteFirst());

System.out.println(user.getRouteFirst());

Gson gson =新的Gson();

Gson gson = new Gson();

TypeToken>令牌=新的TypeToken>(){}; 列出personList = gson.fromJson(user.getRouteFirst(),token.getType());

TypeToken> token = new TypeToken>(){}; List personList = gson.fromJson(user.getRouteFirst(), token.getType());

文章类别为

Article class as

公共类文章{

private String routeFirst;
private String routeSecond;

//设置者和获取者

}

jsp jQuery代码为

jsp jquery code as

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将是,

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Calculator</title>
</head>
<script
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">


$( document ).ready(function() {
    //alert("DOM is ready");
});


function sendJsonData() {

    var article = new Object();
    article.title = "abc";
    article.url = "abc";
    article.categories = [1,2,3];
    article.tags = [1,2,3];

    //alert("JSON string :"+ JSON.stringify(article));

    $.ajax({
        type: 'POST',
        url: "JsonServlet",
        //contentType:"application/json",
        //data:  {point:point},
        data : "point="+encodeURIComponent(JSON.stringify(article)),
        dataType: 'json',
        success: function(result) {

        },
        error: function(e){
        //alert('Error in Processing');
        }

    });
}


</script>

<body>

    <button id="jsonButton" onclick="sendJsonData()">send jdon Data</button>

</body>
</html>

我的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

This is the output that I got in console,

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"]}

希望这会有所帮助.

这篇关于从Jquery发送数组到Struts1方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆