当前位置:   article > 正文

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

前端传递json格式

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

  1. package com.gec.domain;
  2. import lombok.Data;
  3. @Data
  4. public class Person {
  5. private String name;
  6. private int age;
  7. }

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

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

  1. {
  2. "name":"小明",
  3. "age":12
  4. }
  1. //用对象接收json
  2. @PostMapping("/jsonServlet1")
  3. public String jsonServlet1(@RequestBody Person person){
  4. System.out.println("name"+person.getName());
  5. System.out.println("age"+ person.getAge());
  6. // System.out.println("name"+name);
  7. // System.out.println("age"+age);
  8. return "成功";
  9. }

2.前端传递json数组

  1. {
  2. "name":["小明","小王","小刘"],
  3. "age":12
  4. }
  1. //用Map接收json数组
  2. @PostMapping("/jsonServlet4")
  3. public String jsonServlet4(@RequestBody Map hasaMap){
  4. ArrayList arrayList = new ArrayList();
  5. arrayList = (ArrayList) hasaMap.get("name");
  6. String str = (String) arrayList.get(0);
  7. System.out.println("arrayList"+str);
  8. System.out.println("name"+hasaMap.get("name"));
  9. System.out.println("age"+ hasaMap.get("age"));
  10. return "成功";
  11. }

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/509606
推荐阅读
相关标签
  

闽ICP备14008679号