前端如何传数组对象给后端。

前端如果想传一个对象给后端,可以在前端先将其转成字符串的形式,前端代码如下:

//首先获取数组对象中的指定字段
      this.formdata.reviewer = this.formdata.reviewer.map(({username,relatephone,userid})=>{
  return {username,relatephone,userid};
      })
    //然后再将其转成字符串的形式
      let name=[];
      for (var i=0; i < val.length; i++){
        this.formdata.reviewer[i] =JSON.stringify(this.formdata.reviewer[i])
      }
  

后端再接受json字符串的数据之后再处理该对象。


public class Main {
    public static void main(String[] args) {
        //前台给后台提交的数据,常见的有两种格式
        // username=zhangsan&password=123456&age=23
        //{"username":"张三","password":"123456"}
        //把json字符串转换成java对象
        String jsonStr = "{\"username\":\"张三\",\"password\":\"123456\"}";
        String s = jsonStr.replace("{", "").replace("}", "");

        System.out.println(s);
        String[] strings = s.split(",");
        System.out.println(strings[0]);
        System.out.println(strings[1]);

        String[] a = strings[0].split(":");
        System.out.println(a[0]);
        System.out.println(a[1]);

        String[] b = strings[1].split(":");
        System.out.println(b[0]);
        System.out.println(b[1]);

        User user = new User();
        user.setUsername(a[1]);
        user.setPasswrod(b[1]);

        System.out.println(user.getUsername());
        System.out.println(user.getPasswrod());

    }
}
//实例化对象
 class User {
    private String username;
    private String passwrod;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPasswrod() {
        return passwrod;
    }

    public void setPasswrod(String passwrod) {
        this.passwrod = passwrod;
    }

}

你可能感兴趣的:(前端,java,javascript)