【问题标题】:sending array from Jquery to Struts1 method将数组从 Jquery 发送到 Struts1 方法
【发布时间】:2014-03-30 12:12:06
【问题描述】:

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

现在我的北极圈课是

public class Article {

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

//getters and setters
}

现在我遇到了异常 在行

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

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

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

文章用户 = 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;

//setter 和 getter

}

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");
    }

});

【问题讨论】:

  • 我根据您的要求更新我的答案。请检查并告诉我。

标签: java jquery ajax json org.json


【解决方案1】:

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

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

希望这会有所帮助。

【讨论】:

  • 你能提供你的运行代码吗?我试过了,但是把 myJsonData 设置为 null
  • 我使用的是struts1和jsp框架。我把它作为输出点: {"title":"abc","url":"efg","categories":"[1, 2, 3]","tags":"[4, 5, 6] "} com.fasterxml.jackson.databind.JsonMappingException: 无法从 [Source: java.io.StringReader@1a37192; 的 VALUE_STRING 令牌中反序列化 java.util.ArrayList 的实例;行:1,列:27](通过引用链:com.ihexa.common.admin.cabsharing.action.Article["categories"])
  • 在 servlet 和 jsp 中使用您的代码时,它的工作文件就像您使用动态 Web 应用程序给我的输出一样
  • 但您的问题仅限于sending array from Jquery to Servlet。所以你必须关闭这个线程并创建一个新的。
  • 如果你觉得我的answer有用,你可以采纳答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
  • 2010-12-22
相关资源
最近更新 更多