SpringMVC-Json处理

目录

导入依赖

1.使用@ResponseBody

2.使用@RestController

3.使用@RequestBody

3.1定义Handler

3.2Ajax发送json

Jackson常用注解

1.日期格式化

2.属性名修改

3.属性忽略


导入依赖

<!-- Jackson springMVC默认的Json解决方案选择是 Jackson,所以只需要导入jackson的jar,即可使用。-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

1.使用@ResponseBody

@Controller
@RequestMapping("/json")
public class JsonController{    
	@RequestMapping("/test1")
    @ResponseBody //将handler(hello1)的返回值,转换成json(jackson),并将json响应给客户端。
                  //返回的参数类型要与返回值的参数类型保持一致
    public User hello1(){
        System.out.println("hello world");
        User user = new User();
        return user;
    }
 
    // 如果返回值已经是字符串,则不需要转json,直接将字符串响应给客户端 
    @RequestMapping("/test2") 
    @ResponseBody 
    public String hello2(){
        System.out.println("hello world");
        return "你好";
    }
}

2.使用@RestController

Controller类上加了@RestController注解,等价于在类中的每个方法上都加了@ResponseBody

@Controller
@RequestMapping("/json1")
@RestController
public class JsonController{
    @RequestMapping("/test1")
    public User hello1(){
        System.out.println("hello world");
        User user = new User();
        return user;
    }
    //@ResponseBody还可以用在handler的返回值上
    @RequestMapping("/test2")
    public List<User> hello2(){
        System.out.println("hello world");
        List<User> users = Arrays.asList(new User(),new User());
        return users;
    }
}

3.使用@RequestBody

  • 使用@RequestBody注解时,是用于接收Content-Type为application/json类型的请求,数据类型是JSON:{"aaa":"111","bbb":"222"}
  • 不使用@RequestBody注解时,可以接收Content-Type为application/x-www-form-urlencoded类型的请求所提交的数据,数据格式aaa=111&bbb=222  ,form表单提交以及jQuery的.post()方法所发送的请求就是这种类型。

3.1定义Handler

class User{
    private Integer id;
    private String name;
    private Boolean gender;
    //set get
}
@RequestMapping("/users")                      
public String addUser(@RequestBody User user){//@RequestBody将请求体中的json数据转换为java对象,接收json数据
    System.out.println("user:"+user);
    return "index";
}

3.2Ajax发送json

var xhr = new XMLHttpRequest();
xhr.open("post","${pageContext.request.contextPath}/users?"+new Date().getTime());
xhr.setRequestHeader("content-type","application/json");//设置请求头
xhr.send('{"id":1,"name":"shine","gender":"true"}');//传递json串
//ajax
var user = {id:1,name:"shine"};
$.ajax({
    url:'${pageContext.request.contextPath}/json2/test4',
    type:'post',
    contentType:"application/json",//声明请求参数类型为 json
    data:JSON.stringify(user),// 转换js对象成json
    success:function(ret){
        console.log(ret);
    }
});

使用ajax异步获取数据时,必须加上注解@RequestBody,不然后台获取的数据为null

Emp{name='null', password='null', age=0, borndate=null}
<script>
    $(function(){
        $.ajax({
            url:"/json/d4",
            contentType:"application/json",//声明请求参数类型为 json
            type:"post",
            data:JSON.stringify({"name":"张三","age":0,"sex":"男"}),// 转换js对象成json
            success:function(data){
                alert(data);
            }
        })
    })
</script>
   @RequestMapping("/t4")
    @ResponseBody
    public String t4(@RequestBody Emp emp) {
        System.out.println(emp);
        return "haha";
    }

Jackson常用注解

1.日期格式化

@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")

public class User{
	private Integer id;
	private String name;
	@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
	private Date birth;
    ....
    get/set
}

2.属性名修改

@JsonProperty("new_name")

public class User{
	@JsonProperty("new_id") //不再使用原属性名,而是 "new_id"
    private Integer id;
	private String name;
    ....
    get/set
}
输出的json:{“new_id”:xx,"name":"xx"}

3.属性忽略

@JsonIgnore

public class User{
    private Integer id;
    @JsonIgnore // 生成json时,忽略此属性
	private String name;
    ....
    get/set
}
输出json时: {"id":xx}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值