spring boot或springmvc返回时把date类型的字段转成字符串

我们都知道spring boot或者springmvc可以借助自带的jackson直接把实体对象装成json,这次不是分享关于框架如何返回json,而是要给大家分享实体类里的date类型的字段在返回时怎么统一处理成统一返回成string类型

1 使用注解类让其继承JsonSerializer,如下所示

package com.debug;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

public class CustomDateSerializer extends JsonSerializer{

	@Override
	public void serialize(Date value, JsonGenerator jgen, SerializerProvider arg2)
			throws IOException, JsonProcessingException {
		// TODO Auto-generated method stub
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = formatter.format(value);
        jgen.writeString(formattedDate);
		
	}

}

2 把这个类使用注解的方式追加相应字段的getter方法上

public class UserInfo {
	private String name;
	private int id;
	private Date birthday;
	
	@JsonSerialize(using = CustomDateSerializer.class)
	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	
}

3  controller的测试代码

package com.debug;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HiController {
  
   @RequestMapping("/getUserInfo.do")
   public List getUserInfo() {
	   
	   UserInfo u1=new UserInfo();
	   u1.setId(1);
	   u1.setName("justin timberlake");
	   u1.setBirthday(new Date());
	   
	   UserInfo u2=new UserInfo();
	   u2.setId(2);
	   u2.setName("林志颖");
	   u2.setBirthday(new Date());
	   
	   List userList=new ArrayList();
	   userList.add(u1);
	   userList.add(u2);
	
	   return userList;
   }
   
  
}


看下最终的效果



你可能感兴趣的:(Spring,Boot,springmvc)