0

Here is my code

   //javaScript code 

    var sampleDataList= [];

    var dataSample = {
            name:"name",
            id:"id"
    };
    sampleDataList.push(dataSample);
    sampleDataList.push(dataSample);

    $.ajax({
        type : "POST",
        url : "saveData",
        data : sampleDataList,
        //data:mydata,
        contentType : "json",
        async:false,
        success : function(data) {
        },error: function(XMLHttpRequest, textStatus, errorThrown) {
        }
    });

    //TO class

    public class DataSample {
        private String name;
        private String id;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
    }

    //Controller

    @RequestMapping(value = "/saveData", method = RequestMethod.POST)
        public void saveDatas(ArrayList<DataSample> dataSamp){
            System.out.println(asdf);
        }

am able to hit the conttroller but dataSamp(parameter of saveDatas method) doesnot have any value. It is received as empty list.

Please suggest what went wrong in my code ? or please me how get this done ?

5

1 Answer 1

1

Use JSON.stringify() when sending ajax-request:

$.ajax({
        type : "POST",
        url : "saveData",
        data : JSON.stringify(sampleDataList),
        //data:mydata,
        ...

And if I'm not mistaken also you need @RequestBody annotation in request parameter :

@RequestMapping(value = "/saveData", method = RequestMethod.POST)
        public void saveDatas(@RequestBody ArrayList<DataSample> dataSamp){
            System.out.println(asdf);
        }

Add jackson dependency for converting json to object and vice versa

<dependency><!-- jackson -->
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version></version>
  </dependency>
Sign up to request clarification or add additional context in comments.

2 Comments

where do i need to add the jackson dependency conversion , in web.xml?
add to the pom.xml file if you are using maven.

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.