0


前端传递Json格式,后端如何用多种方式接收

一、先定义一个简单的实体类

package com.gec.domain;

import lombok.Data;

@Data
public class Person {
    private String name;
    private int age;
}

二、编写前端传递的json数据

1.前端传递普通json,后端用对象接收

{
    "name":"小明",
     "age":12
}
 //用对象接收json
    @PostMapping("/jsonServlet1")
    public String jsonServlet1(@RequestBody Person person){
        System.out.println("name"+person.getName());
        System.out.println("age"+ person.getAge());

//        System.out.println("name"+name);
//        System.out.println("age"+age);
        return "成功";
    }

2.前端传递json数组,

{
    "name":["小明","小王","小刘"],
     "age":12
}
//用Map接收json数组
    @PostMapping("/jsonServlet4")
    public String jsonServlet4(@RequestBody Map hasaMap){
        ArrayList arrayList = new ArrayList();
        arrayList = (ArrayList) hasaMap.get("name");
        String str = (String) arrayList.get(0);
        System.out.println("arrayList"+str);
        System.out.println("name"+hasaMap.get("name"));
        System.out.println("age"+ hasaMap.get("age"));

        return "成功";
    }

3.前端传递json数组,后端用集合接收Josn数组

{
    "name":["小明","小王","小刘"]
}
 //用Map嵌套list接收json数组
    @PostMapping("/jsonServlet5")
    public String jsonServlet5(@RequestBody  Map<String,List > hasaMap){
        System.out.println("name"+hasaMap.get("name"));
        System.out.println("age"+hasaMap.get("age"));

        return "成功";
    }
标签: java json intellij-idea

本文转载自: https://blog.csdn.net/weixin_56877622/article/details/126779802
版权归原作者 weixin_56877622 所有, 如有侵权,请联系我们删除。

“前端传递Json格式,后端如何用多种方式接收”的评论:

还没有评论