I have a Json writer class EntrenadorWriter
that writes the entity data produced from a RestFul service into a Json file. Then, the file is consumed by Json reader class. One of the fields that has to be written into the Json is a Java.util.Date Date. But I'm having serious trouble to write-read the Date.
来自Json writer类的WriteTo方法:
@Override
public void writeTo(Usuario t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException, WebApplicationException {
JsonGenerator gen = Json.createGenerator(entityStream);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
gen.writeStartObject()
.write("Dni", t.getDni())
.write("PassWord", t.getPassWord())
.write("Login", t.getLogin())
.write("Email", t.getEmail())
.write("NombreCompleto", t.getNombreCompleto())
.write("Telefono", t.getTelefono())
.write("FechaNacimiento", df.format(t.getFechaNacimiento()))
.writeEnd();
gen.flush();
}
这是问题开始的地方:
.write("FechaNacimiento", df.format(t.getFechaNacimiento()))
t.getFechaNacimiento()
returns a java.util.Date
and df.format()
parses it to String with the format specified in the DateFormatter
(yyyy-MM-dd).
json被写入并发送。
来自Json阅读器类的ReadTo方法:
public Usuario readFrom(Class<Usuario> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
InputStream entityStream)
throws IOException, WebApplicationException {
Usuario usuario = new Usuario();
JsonParser parser = Json.createParser(entityStream);
while (parser.hasNext()) {
switch (parser.next()) {
case KEY_NAME:
String key = parser.getString();
parser.next();
switch (key) {
case "Dni":
usuario.setDni(key);
break;
case "FechaNacimiento":
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.parse(key, formatter);
usuario.setFechaNacimiento(java.sql.Date.valueOf(localDate));
break;
default:
break;
}
break;
default:
break;
}
}
return usuario;
}
读取器使用Json中的date字段,并将字符串date解析为LocalDate对象。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.parse(key, formatter);
I've made this convertion by looking in the internet and what i found was, that so as to parse Dates with "yyyy-MM-dd" format, without the time zone part, is more correct in this way than using directly a convertion to a Date Object. Then DateTime object is parsed into a java.sql.date java.sql.Date.valueOf(localDate)
.
错误是以下之一:
javax.ws.rs.client.ResponseProcessingException: javax.json.bind.JsonbException: Error parsing date from value: 1998-04-19