spring mvc与Json数据交互

一、 Spring mvc与Json数据交互

背景知识:

以前(单体项目):一个项目中既包含后端的controller接口还有视图(jsp/html)。
现在(前后端分离项目):后端使用Java开发,通过json将数据返回给前端、而前端使用前端框架开发的项目如vue.js 、angular.js、layui等,部署在前端服务器上通过Ajax请求,请求后端接口的数据。

二、Controller方法返回值为JSON格式数据 与请求参数为JSON格式数据

1. @RequestBody

作用:

@RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容转换为json、xml等格式的数据并绑定到controller方法的参数上。

2. @ResponseBody

作用:

该注解用于将Controller的方法返回的对象,通过HttpMessageConverter接口转换为指定格式的数据如:json,xml等,通过Response响应给客户端。

三、RequestMapping限制接口的请求方式

@RequestMapping(value=“test/jsonObj”,method=RequestMethod.GET)
表明这个接口使用get方式进行请求,其他非get请求,无法访问这个接口。

    @RequestMapping(value="test/jsonObj",method=RequestMethod.GET)
    @ResponseBody  //注解的作用 1.将返回的结果序列化为json字符串 2.不会使用视图解析器
    public List<Users> testJsonObj() {
    
    
         List<Users> users = iUsersService.list(1, 3);
        return users;
    }
   @RequestMapping(value="/save/user",method=RequestMethod.POST)
    @ResponseBody  //注解的作用 1.将返回的结果序列化为json字符串 2.不会使用视图解析器
    public  ServerResponse<Users>  saveUser(@RequestBody Users users) {
    
    
        System.out.println("users==>"+users);
        //1.逻辑操作......
        
        return ServerResponse.SuccessResponse();
    }

四、序列化和反序列化

4.1 什么是序列化和反序列化

序列化:将对象数据转为二进制数据。
反序列化:将二进制数据转为对象数据。

4.2 .什么时候需要序列化和反序列化
  1. 要将对象数据保存磁盘或缓存(内存)。
  2. 需要将对象通过网络传输,网络上只能按字节传。
4.3.序列化的方式
		实现Serializable接口

五、JSON序列化

1、controller方法的返回如果是自定义类型,需要在类上加上JSON序列化的注解
  @JsonSerialize(include =  JsonSerialize.Inclusion.NON_NULL)
   public class ServerResponse<T> implements Serializable{
    
    
      include =  JsonSerialize.Inclusion.NON_NULL:非null属性才会被json序列化
            
  }
2、如果类的某个属性希望被json序列化,如何处理?
  @JsonIgnore
  private int age;//不想被JSON序列化 

猜你喜欢

转载自blog.csdn.net/weixin_46822085/article/details/109009168