spring boot gradle 后端接收前端ajax传递来的json数组字符串并转化为对象数组

首先在build.gradle文件中添加:

compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.8'

后端建好数据对象:

package com.exampleb.demob;

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

然后写好接收数据的controller:

@RequestMapping(value="/test")
    @ResponseBody
    public String test(@RequestParam String users) throws IOException {
        // 业务处理
        System.out.println(users);

        ObjectMapper mapper=new ObjectMapper();
        com.fasterxml.jackson.databind.type.ArrayType arrayType = mapper.getTypeFactory().constructArrayType(Person.class);
        Person[] persons = mapper.readValue(users, arrayType);
        for(Person person:persons){
            System.out.println("person id and name: "+person.getId()+" ---> "+person.getName());
        }
        return users;
    }

前端提交数据的网页:




    
    test
    


    
    


 

你可能感兴趣的:(java,JavaScript,spring,boot,gradle,json,array,转换)