简体   繁体   English

如何在spring-mvc控制器中重复提取从ajax请求发送的数据作为对象的Json数组?

[英]How to extract data which is sent from ajax request as a Json Array of objects repetitively in spring-mvc controller?

I am sending a set of data as Json Array of objects from ajax function to my spring mvc controller method. 我正在将一组数据作为对象的Json数组从ajax函数发送到我的spring mvc控制器方法。 ie. 即。

[{"item":"Cheese Lover","size":"960.00","qty":"1"},{"item":"Garlic Bread","size":"390.00","qty":"1"},{"item":"pudding3","size":"420.00","qty":"2"}]

I need to extract these data separately as item, size and qty so that I can feed the fields to sql and send the data to database. 我需要分别提取这些数据作为项目,大小和数量,以便可以将字段输入sql并将数据发送到数据库。 But I am got stuck here as I have no idea how to do it properly and this is the controller method which I have used so far. 但是我被困在这里,因为我不知道如何正确地做,这是我到目前为止使用的控制器方法。

 @RequestMapping(value = "/add_package")
    public @ResponseBody
    String addPackage(@ModelAttribute("command") Package newPackage,
                      // @RequestBody PackageContent[] content,
                      HttpServletRequest request){
        PackageContent packageContent = new PackageContent();
        String s=request.getParameter("test");

        ObjectMapper objectMapper=new ObjectMapper();
        JSONObject obj= new JSONObject();

        try {
            obj=objectMapper.readValue(s, JSONObject.class);
            obj.get(packageContent.getItem());

            /*for(PackageContent content1 : s){
                //System.out.println(content1.getItem());
                LOGGER.trace("hhh  "+content1.getItem());
            }*/

        } catch (Exception e) {
            LOGGER.error("error {}",e);
        }

        return obj.toString();}

When I log the result in console,in ajax success function it shows only as {} . 当我将结果记录到控制台中的ajax成功函数中时,它仅显示为{} I am doing this on form submit button click and is it wrong to do so? 我是在表单提交按钮单击时执行此操作的,这样做有错吗? If so when and how can I extract these data repetitively in controller so that send them to the sql code? 如果是这样,何时以及如何在控制器中重复提取这些数据,以便将它们发送到sql代码?

    Class ListOfItems{
    List<Items> listItems;
    //Getters and Setters

// Use Jackson Here to Convert 
ListOfItems itemList = new ObjectMapper().readValue(jsonString, ListOfItems.class);
}
    class Items{
    private String item;    
    private String qty;    
    private String size;

//Getters and Setters compulsary because Jackson internally uses getters    
//to set the value     
}    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM