Issue
I'm new to Spring, so I apologize if the question is basic.
I'm writing an application which fetches data from postgres and returns as JSON. The table structure is as below:
table student{
id int,
created_time Timestamp
}
I have an entry in the table as:
id | created_time
---+---------------------------
1 | 2015-02-19 23:58:23.579761
I'm having my entity object as:
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;
}
}
And this is how I'm returning the data:
@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
}
However, the json I get is:
{"id":1,"created_time":1424419103579}
Why is it returning junk value for time stamp? How do I get the original value in same format as is in the table?
Thanks in advance.
Solution
This is the default behaviour.
By default Jackson uses default strategy to determine the date formatting when serializating into JSON, so you get date in milliseconds.
To override this with custom behavior, you can use @JsonSerialize annotation.
You will need a custom Date serializer, for example
@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);
}
}
And then, in your entity you can do
@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;
}
}
P.S. If you named your field as created_time
only to be able to serialize your property into json having created_time
as a name, better to use instead @JsonProperty.
@JsonProperty("created_time")
@JsonSerialize(using=JsonDateSerializer.class)
protected Timestamp createdTime;
Answered By - vtor
Answer Checked By - Cary Denson (JavaFixing Admin)