How we can access the array objects of javascript

2019-08-14 07:57发布

问题:

I need to access array objects of javascript passed through ajax in java. I am using dojo.

This is how I tried to pass values through dojo ajax call.

Javascript

var arrayObj = [{'id': 4, 'label': 'first', 'value': 'success'}, {'id': 6, 'label': 'second', 'value': 'failed'}];

dojo.xhrPost({       
  url: "test/deleteItems.json",
  content: { items: arrayObj },
  handleAs: "json",
  load: function(response) {
    alert('got response');
  }
});

In Java(Spring MVC), I tried with List of String, array of Strings in java controller to access the items passed through Javascript Ajax. But none of them got worked with retrieving exact objects passed from Javascript.

Java

@RequestMapping(value="deleteItems", produces = "application/json")
     public @ResponseBody String deleteItems(
             @RequestParam(required = true) String[] items
             //@Valid @RequestBody List<AnalysisBean> pcptBean
             ) {
       /* I need to access the array objects passed from javascript here. */

}

How to retrieve the array objects in java controller?

Note: I tried with pass multidimensional array through Ajax to java controller.

var arrayObj = [[4,'first', 'success'],[6, 'second', 'failed']];

But it didn't work too.

I would like to get solution using Dojo/jQuery. Any help will be greatly appreciated.

回答1:

You can use the ObjectMapper class from Jackson Library to parse your array of objects. Here is the way you can do it:

ObjectMapper mapper = new ObjectMapper();

YourClass[] objects = mapper.readValue(items, YourClass.class);

BR.