java - @JsonIgnore 不适用于 Spring Boot 应用程序

标签 java json rest spring-boot

我正在创建一个 RESTful Web 服务。一切正常,除非我在具有 @OneToMany 关系的类之一中添加 @JsonIgnore 注释。我得到:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0]->com.packt.cardatabase.domain.Car["owner"]->com.packt.cardatabase.domain.Owner$HibernateProxy$AcLDWRSD["hibernateLazyInitializer"])

我的pom.xml:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.5.0</version>
    </dependency>
</dependencies>

我的 Controller :

@RestController
public class CarController {
    @Autowired
    private CarRepository repository;

    @RequestMapping("/cars")
    public Iterable<Car> getCars(){
       return repository.findAll();
    }
}

我的实体:

@Entity
@Table(name = "owner")
public class Owner {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long ownerid;
    private String firstname, lastname;
    @OneToMany(cascade =CascadeType.ALL, mappedBy="owner")

    @JsonIgnore <---- My problem
    private List<Car> cars;

    public Owner() {
    }
        ....
}

当我删除@JsonIgnore时,我可以从数据库中获取序列化数据。但当我添加注释时,不是 JSON 格式。

最佳答案

在您的 Car 类中,将其添加到您的“所有者”声明上方:

 @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})

关于java - @JsonIgnore 不适用于 Spring Boot 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55458173/

相关文章:

java - 每次测试前加载 SQL 数据库

java - 无法使用 Gson 将 JSON 反序列化为 HashMAp<String, POJO>

java - vertx future 失败但被视为成功()

python - 处理请求中的 ValueError 后没有值?

javascript - 通过 ID 连接两个 Javascript/JSON 对象的最快方法

java - Keycloak 强制刷新 token

java - 确定程序与哪个 Java 版本(或 Eclipse 版本)兼容

rest - 如何防止在 REST api GET 中向不同客户端发送相同数据?

ruby-on-rails - 从 ActiveResource 请求中删除 .xml 扩展名

javascript - d3.js:如何遍历备份 DOM