JSON 解析错误:无法构造 java.time.LocalDate 的实例:没有从字符串值反序列化的字符串参数构造函数/工厂方法 [英] JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

查看:61
本文介绍了JSON 解析错误:无法构造 java.time.LocalDate 的实例:没有从字符串值反序列化的字符串参数构造函数/工厂方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Spring Data REST 项目的新手,我正在尝试创建我的第一个 RESTful 服务.任务很简单,但我卡住了.

I am new to Spring Data REST project and I am trying to create my first RESTful service. The task is simple, but I am stuck.

我想使用 RESTful API 对存储在嵌入式数据库中的用户数据执行 CRUD 操作.

I want to perform CRUD operations on a user data stored in an embedded database using RESTful API.

但我不知道如何让 Spring 框架将birthData 处理为1999-12-15"并将其存储为LocalDate.@JsonFormat 注释没有帮助.

But I cannot figure out how to make the Spring framework process the birthData as "1999-12-15" and store it as a LocalDate. The @JsonFormat annotation does not help.

目前我收到错误:

HTTP/1.1 400 
Content-Type: application/hal+json;charset=UTF-8
Transfer-Encoding: chunked
Date: Thu, 24 Aug 2017 13:36:51 GMT
Connection: close

{"cause":{"cause":null,"message":"Can not construct instance of java.time.LocalDate: 
no String-argument constructor/factory method to deserialize from String value ('1999-10-10')
 
at [Source: org.apache.catalina.connector.CoyoteInputStream@4ee2a60e; 
line: 1, column: 65] (through reference chain: ru.zavanton.entities.User["birthDate"])"},
"message":"JSON parse error: Can not construct instance of java.time.LocalDate: 
no String-argument constructor/factory method to deserialize from String value ('1999-10-10'); nested exception is com.fasterxml.jackson.databind.JsonMappingException: 
Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value ('1999-10-10')
 
at [Source: org.apache.catalina.connector.CoyoteInputStream@4ee2a60e; line: 1, column: 65] (through reference chain: ru.zavanton.entities.User["birthDate"])"}

如何使它工作,以便客户端调用:

How to make it work, so that client calls like:

curl -i -X POST -H "Content-Type:application/json" -d "{  "firstName" : "John",  "lastName" : "Johnson", "birthDate" : "1999-10-10", "email" : "john@example.com" }" http://localhost:8080/users

实际上会将实体存储到数据库中.

will actually store the entity into the database.

以下是课程信息.

用户类:

package ru.zavanton.entities;


import com.fasterxml.jackson.annotation.JsonFormat;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.time.LocalDate;

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String firstName;
    private String lastName;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
    private LocalDate birthDate;

    private String email;
    private String password;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public LocalDate getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(LocalDate birthDate) {
        this.birthDate = birthDate;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

UserRepository 类:

The UserRepository class:

package ru.zavanton.repositories;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import ru.zavanton.entities.User;

@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRepository extends PagingAndSortingRepository<User, Long> {

    User findByEmail(@Param("email") String email);

}

应用类:

package ru.zavanton;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);

    }
}

推荐答案

你需要这个序列化和反序列化的 jackson 依赖.

You need jackson dependency for this serialization and deserialization.

添加此依赖项:

摇篮:

compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.4")

马文:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

之后,您需要告诉 Jackson ObjectMapper 使用 JavaTimeModule.要做到这一点,在主类中自动装配 ObjectMapper 并向其注册 JavaTimeModule.

After that, You need to tell Jackson ObjectMapper to use JavaTimeModule. To do that, Autowire ObjectMapper in the main class and register JavaTimeModule to it.

import javax.annotation.PostConstruct;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

@SpringBootApplication
public class MockEmployeeApplication {

  @Autowired
  private ObjectMapper objectMapper;

  public static void main(String[] args) {
    SpringApplication.run(MockEmployeeApplication.class, args);

  }

  @PostConstruct
  public void setUp() {
    objectMapper.registerModule(new JavaTimeModule());
  }
}

在那之后,您的 LocalDate 和 LocalDateTime 应该正确序列化和反序列化.

After that, Your LocalDate and LocalDateTime should be serialized and deserialized correctly.

这篇关于JSON 解析错误:无法构造 java.time.LocalDate 的实例:没有从字符串值反序列化的字符串参数构造函数/工厂方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆