序列化实体会返回Spring中时间戳的垃圾值



我是Spring的新手,所以如果问题是基本的,我很抱歉。

我正在编写一个应用程序,它从postgres获取数据并以JSON形式返回。表格结构如下:

table student{
id int,
created_time Timestamp
}

我在表格中有一个条目:

 id | created_time           
 ---+---------------------------
 1  | 2015-02-19 23:58:23.579761

我的实体对象为:

package main.java;
import java.sql.Timestamp;
import javax.persistence.Entity;
import javax.persistence.Id;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@JsonIgnoreProperties(ignoreUnknown = true)
public class Student {
    @Id
    protected int id;
    protected Timestamp created_time;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public Timestamp getCreated_time() {
        return created_time;
    }
    public void setCreated_time(Timestamp created_time) {
        this.created_time = created_time;
    }
}

这就是我返回数据的方式:

@RestController
@RequestMapping(value = "/student", produces = MediaType.APPLICATION_JSON_VALUE)
public class StudentController {
    @Autowired
    protected StudentRepository studentRepository;
    @RequestMapping(value = "/{id}")
    public Student student(@PathVariable int id) {
        return studentRepository.findOne(id);// uses the findOne() method inherited from CrudRepository
    }

然而,我得到的json是:

{"id":1,"created_time":1424419103579}

为什么它为时间戳返回垃圾值?如何获得与表中相同格式的原始值?

提前谢谢。

这是默认行为。

默认情况下,Jackson在序列化为JSON时使用默认策略来确定日期格式,因此您可以获得以毫秒为单位的日期。

若要使用自定义行为覆盖此项,可以使用@JsonSerialize注释。

您将需要一个自定义的日期序列化程序,例如

@Component
public class JsonDateSerializer extends JsonSerializer<Timestamp> {
        private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        @Override
        public void serialize(Timestamp date, JsonGenerator gen, SerializerProvider provider)
                throws IOException, JsonProcessingException {
            String formattedDate = dateFormat.format(date);
            gen.writeString(formattedDate);
        }
    }

然后,在你的实体中,你可以进行

@Entity
@JsonIgnoreProperties(ignoreUnknown = true)
public class Student {
    @Id
    protected int id;
    protected Timestamp created_time;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    @JsonSerialize(using=JsonDateSerializer.class)
    public Timestamp getCreated_time() {
        return created_time;
    }
    public void setCreated_time(Timestamp created_time) {
        this.created_time = created_time;
    }
}

附言:如果您将字段命名为created_time只是为了能够将属性序列化为以created_time为名称的json,那么最好使用@JsonProperty。

 @JsonProperty("created_time")
 @JsonSerialize(using=JsonDateSerializer.class)
 protected Timestamp createdTime;

最新更新