我用jersy client
编写了一个网络服务并将 json 字符串转换为 bean 类,但日期显示错误。我尝试@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
但它仍然在方法中给出相同的错误。如何在我的代码中将字符串转换为日期格式。
错误:
not a valid representation (error: Failed to parse Date value 'Aug 7, 2017 1:35:00 PM': Can not parse date "Aug 7, 2017 1:35:00 PM": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
网络服务
@POST
@Path("/driverLocation")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response handleDriverLocation(String jsonRequest) {
List<DriverLocationDetails> driverLocationDetails = bookingService
.getLocationDetailsFromDB();
boolean save = false;
for (DriverLocationDetails details : driverLocationDetails) {
Gson g = new Gson();
jsonRequest = g.toJson(details);
DriverLocationDetails driverLocationDetail = TmsUtil
.readAsObjectOf(DriverLocationDetails.class, jsonRequest);
save = bookingService.saveLocation(driverLocationDetail);
}
JSONObject jo = new JSONObject();
try {
if (save) {
jo.put("Save", "saved");
} else {
jo.put("Save", "failed");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Response.status(200).entity(jo.toString()).build();
}
static com.fasterxml.jackson.databind.ObjectMapper MAPPER = new ObjectMapper();
public static <T> T readAsObjectOf(Class<T> clazz, String value) {
try {
return MAPPER.readValue(value, clazz);
} catch (Exception e) {
logger.error("{}, {}", e.getMessage(), e.fillInStackTrace());
}
return null;
}
安慰
Can not construct instance of java.util.Date from String value 'Aug 7, 2017 1:35:00 PM': not a valid representation (error: Failed to parse Date value 'Aug 7, 2017 1:35:00 PM': Can not parse date "Aug 7, 2017 1:35:00 PM": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
at [Source: java.io.StringReader@4d768e3c; line: 1, column: 72] (through reference chain: in.greenorange.model.DriverLocationDetails["gpsLocationTime"]), com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.util.Date from String value 'Aug 7, 2017 1:35:00 PM': not a valid representation (error: Failed to parse Date value 'Aug 7, 2017 1:35:00 PM': Can not parse date "Aug 7, 2017 1:35:00 PM": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
at [Source: java.io.StringReader@4d768e3c; line: 1, column: 72] (through reference chain: in.greenorange.model.DriverLocationDetails["gpsLocationTime"])
您的模式必须如下所示:
@JsonFormat(pattern = "MMM d',' yyyy HH:mm:ss a")
因为这是从服务器获得的模式
我只是使用 GSon 进行转换,因为杰克逊有转换
DriverLocationDetails driverLocationDetail = g.fromJson(jsonRequest, DriverLocationDetails.class);