Я использую Java Spring MVC с базой данных MySql, и я пытаюсь использовать REST api.
Проблема с полями даты, здесь моя модель:
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "patient_mesure")
@JsonAutoDetect
public class PatientMesure {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "mesure_patient")
private float mesure_patient;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "mesure", nullable = false)
private Mesure mesure;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "patient", nullable = false)
private Personne patient;
@Column(name = "date")
private Date date;
@Column(name = "inserted", nullable = false)
private Date inserted;
@Column(name = "updated", nullable = false)
private Date updated;
// getters and setters
}
И вот мой контроллер отдыха:
import com.eheio.spring.models.PatientMesure;
import com.eheio.spring.models.Personne;
import com.eheio.spring.services.PatientMesureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
@RestController
public class PatientMesureRestController {
private PatientMesureService patientMesureService;
@Autowired
public void setPatientMesureService(PatientMesureService patientMesureService) {
this.patientMesureService = patientMesureService;
}
@GetMapping(value = "/getAllMesures")
public List<PatientMesure> listAllUsers(HttpServletRequest httpServletRequest) {
HttpSession httpSession = httpServletRequest.getSession(true);
Personne personne = (Personne) httpSession.getAttribute("personne");
return patientMesureService.findMesuresByPatient(personne.getId());
}
}
результаты, которые я получаю:
{ id: 1, date: 1527801252000, inserted: 1527801252000, mesure_patient: 50, updated: 1527801252000}
Как я могу получить правильную форму для полей даты? что-то вроде 2018-05-31 21:14:12
Установите пользовательский JsonSerialize и отформатируйте его там, используя SimpleDateFormat следующим образом:
Сначала создайте класс JsonDateSerializer:
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
import org.springframework.stereotype.Component;
@Component
public class JsonDateSerializer extends JsonSerializer<Date>{
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
@Override
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
throws IOException, JsonProcessingException {
String formattedDate = dateFormat.format(date);
gen.writeString(formattedDate);
}
}
а затем в вашем методе получения:
@JsonSerialize(using=JsonDateSerializer.class)
public Date getDate() {
return date;
}
Кроме того, вы используете Java 8, есть DateTimeFormatter, который является потокобезопасным (как отметил @Philippe Marschall):
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
Вы можете использовать, как показано ниже
import com.fasterxml.jackson.annotation.JsonFormat;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss.SS a")
@Column(name = "date")
private Date date;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss.SS a")
@Column(name = "inserted", nullable = false)
private Date inserted;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss.SS a")
@Column(name = "updated", nullable = false)
private Date updated;
SimpleDateFormat
они не являются потокобезопасными.