JSON解析错误:无法反序列化值

时间:2018-02-23 09:01:33

标签: java json

尝试创建实体的arraylist时出现以下错误 - “timelog”。

{
    "timestamp": 1519372691473,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.http.converter.
                  HttpMessageNotReadableException",
    "message": "JSON parse error: Can not deserialize value of type 
                java.time.LocalDate from String \"02-17-2018\": Text '02-17-
                2018' could not be parsed at index 0; nested exception is 
                com.fasterxml.jackson.databind.exc.InvalidFormatException: 
                Can not deserialize value of type java.time.LocalDate from 
                String \"02-17-2018\": Text '02-17-2018' could not be parsed 
                at index 0\n at [Source: 
                java.io.PushbackInputStream@83d3114; line: 3, column: 14] 
                (through reference chain: java.util.ArrayList[0] 
                >com.timesheet.model.Timelog[\"logDate\"])",
    "path": "/employee/101/timelog/tabdata"
}

我通过'post'method发送一组实体记录。我在执行请求体时遇到错误。

@RequestMapping(path = "employee/{id}/timelog/tabdata", method = 
RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public void timeLogging(@RequestBody ArrayList<Timelog> tabData, 
@PathVariable("id") Integer id) {
    //Employee e = employeeRepository.findOne(id);
    //tabData.forEach(log -> {
    //log.setEmployee(e);
    //timeLogRepository.save(log);
    //});

    }

在我的实体中,我使用的是localdatedeserializer: 时间日志实体代码:

@Entity
@Table(name = "timelog", catalog = "timesheet")
public class Timelog implements java.io.Serializable {

    private static final long serialVersionUID = 1871977717947082854L;
    private Integer id;
    @JsonIgnore
    private Employee employee;

    @JsonDeserialize(using = LocalDateDeserializer.class)
    private LocalDate logDate;
    private String project;
    private Float timetaken;

// LocalDateDeserializer的代码

public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {
    public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("MM-dd-yyyy");

    @Override
    public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        return LocalDate.parse(p.getValueAsString(), FORMATTER);
    }
}

任何人都可以帮助确定localdatedeserializer没有生效的原因。谢谢。

1 个答案:

答案 0 :(得分:1)

当通过网络传递日期和时间作为日期和时间时,您必须解决诸如格式化之类的问题。 如果您可以控制应用程序的前端,我建议您使用毫秒(这只是一个长期的#39;)并在您真正需要时处理演示文稿(格式化)(通常是几个地方)