0

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

    });

and my java code as

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

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

i get json as follows

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

actually it should be

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

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

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

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

Gson gson = new Gson();

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

Article class as

public class Article {

private String routeFirst;
private String routeSecond;

//setters and getters

}

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

});
1
  • I update my answer as per your requirement.Please check it and let me know. Commented Feb 27, 2014 at 12:37

1 Answer 1

1

My jsp will be ,

<!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>

My servlet will be ,

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

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

Hope this helps.

Sign up to request clarification or add additional context in comments.

5 Comments

Can you provide your running code please.I have tried this but getting myJsonData as null
I am using struts1 and jsp framework. I got this as output Point : {"title":"abc","url":"efg","categories":"[1, 2, 3]","tags":"[4, 5, 6]"} com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token at [Source: java.io.StringReader@1a37192; line: 1, column: 27] (through reference chain: com.ihexa.common.admin.cabsharing.action.Article["categories"])
When using your code in servlet and jsp it works file like what u have given me as output using a dynamic web application
But your question is sending array from Jquery to Servlet only. So you have to close this thread and make a new one.
If you feel , my answer is useful,you can accept the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.