后端如何接受前端传过来的Json数据

使用Json前提:

引入依赖

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.9</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.9</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.9</version>
        </dependency>

SpringMVC配置

<mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"></property>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

方式一:前端传递Json对象 <== Ajax默认格式

  <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
  <script>
  <!--Json对象-->
    var user = {
      "username": "hahah",
      "password": "123456"
    };

    $.ajax({
      url:"/testJson",
      type: "GET",
      async: true,
      data: user,//Json对象
      dataType: 'json',
      success: function (data) {

      }
    });
  </script>
public class User {
    private String username;
    private String password;
    //get、set方法
    }

(1)可省略@RequestParam注解

@Controller
public class TestJson {
    @RequestMapping("/testJson")
    @ResponseBody
    public String testJson(User user,String username,String password){
        System.out.println(user.getUsername());//hahah
        System.out.println(user.getPassword());//123456
        System.out.println(username);//hahah
        System.out.println(password);//123456
       return "aaaa";
    }
}

(2) 加@RequestParam注解

    @RequestMapping("/testJson2")
    @ResponseBody
    public String testJson2(@RequestParam String username,@RequestParam String password){
        System.out.println(username);//hahah
        System.out.println(password);//123456
        return "aaaa";
    }

优点:

(1)前端传递数据不用转换为Json字符串:Json.stringify(user)
(2)后端接收参数灵活:
                  ①可以是封装对象 (User)
                  ②可以是单个参数(username,password)
                  ③可以封装对象与单个参数混用(User,username或password)

方式二:传递JSON字符串给后端 <== 使用application/json格式

Content-Type使用application/json的时候,要将JSON对象转换为JSON字符串

<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>

  <script>
    var user = {
      "username": "hahah",
      "password": "123456"
    };

    $.ajax({
      url:"/testJson3",
      type: "POST",
      async: true,
      contentType: "application/json;charset=UTF-8", //使用 application/json;charset=UTF-8
      data: JSON.stringify(user), //将JSON对象转换为JSON字符串
      dataType: 'json',
      success: function (data) {

      }
    });
  </script>

后端接收前端Json字符串

① 后端接收前端Json字符串,只能封装在User对象中,不能单独设置参数。

    @RequestMapping(value = "/testJson3",method = {RequestMethod.POST})
    @ResponseBody
    public String testJson3(@RequestBody User user){
        System.out.println(user.getUsername());//hahah
        System.out.println(user.getPassword());//123456
        return "aaaa";
    }

② 后端接收前端Json字符串,封装到Map中

    @RequestMapping(value = "/testJson4",method = {RequestMethod.POST})
    @ResponseBody
    public String testJson4(@RequestBody Map map){
        System.out.println(map.get("username"));//hahah
        System.out.println(map.get("password"));//123456
        return "aaaa";
    }

③ 后端接收前端Json字符串,用String接收

    @RequestMapping(value = "/testJson5",method = {RequestMethod.POST})
    @ResponseBody
    public String testJson5(@RequestBody String user) throws IOException {
        System.out.println(user); // {"username":"hahah","password":"123456"}
        ObjectMapper mapper = new ObjectMapper();
        User user1 = mapper.readValue(user, User.class);
        System.out.println(user1.getUsername());//hahah
        System.out.println(user1.getPassword());//123456
        return "aaaa";
    }

优点:

(1)前端需要使用JSON.stringify()将JSON对象转为JSON字符串
(2)后端接收参数比较麻烦,没有第一种简单,也没有第一种灵活。

  • 55
    点赞
  • 257
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值