gpt4 book ai didi

java - 忽略 jackson 属性(property)

转载 作者:行者123 更新时间:2023-12-01 09:50:57 25 4
gpt4 key购买 nike

{admin": false,
"email": "student@student.com",
"firstName": "Student",
"idGroup": {
"idGroup": 1,
"name": "BlijkbaarGeenGroep",
"teacher": {
"admin": true,
"email": "1",
"firstName": "Example",
"idUser": 1,
"lastName": "User",
"teacher": true
}
}

返回以下内容。我想让 jackson 做的就是无视老师。我不太关心这次通话中的老师元素。问题是我不想访问 GroupEntity,因为有时我确实需要 groupinfo。

     package org.hva.folivora.daomodel.user;

import com.owlike.genson.annotation.JsonIgnore;
import com.owlike.genson.annotation.JsonProperty;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonIgnoreType;
import org.hva.folivora.daomodel.global.GroupEntity;

import javax.persistence.*;
import java.io.Serializable;

/**
* @author
*/
@Entity
@Table(name = "Student", schema = "pad_ijburg", catalog = "")
public class StudentEntity extends UserEntity implements Serializable {
private GroupEntity idGroup;

public StudentEntity(String email, String firstName, String lastName, String password, GroupEntity idGroup) {
//A student cannot be an admin or teacher. (False, False)
super(email, firstName, lastName, password, false, false);
this.idGroup = idGroup;
}

public StudentEntity() {

}

//Something like ignore all but idgroup??!
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "idGroup")
public GroupEntity getIdGroup() {
return idGroup;
}

public void setIdGroup(GroupEntity idGroup) {
this.idGroup = idGroup;
}

}

最佳答案

您有多种选择:

  1. @JsonIgnoreProperties 放在您的 StudentEntity 类上。请参阅:JsonIgnoreProperties (Jackson-annotations 2.7.4 API) .

  2. StudentEntity 编写自定义 JsonSerializer。在这里,您必须编写用于构造输出 JSON 的每个字段的代码。请参阅:Jackson - Custom Serializer | Baeldung .

  3. 使用 Mixin,它基本上是一个与您的 StudentEntity 相匹配的接口(interface)。在这里,您可以在 getTeacher() 方法上使用 @JsonIgnore。请参阅:JacksonMixInAnnotations · FasterXML/jackson-docs Wiki · GitHub .

  4. @JsonSerialize 放在 StudentEntity 类中的 idGroup 属性上。该注释采用一个类作为实现 JsonSerializer 的参数。不过,当(且仅当)Jackson 序列化 StudentEntity 实例时,您可以指定序列化 idGroup 属性的方法。 (这或多或少类似于选项2。,但实现起来更简单)

  5. 编写与您的输出格式匹配的 DTO 类。然后将 StudentEntity 对象中的字段逐个复制到 StudentEntityDTO 对象(该对象没有 teacher 属性),然后让 Jackson 序列化DTO 对象而不是原始的 StudentEntity 对象。这需要编写大量代码,并且只有在输出 JSON 与原始对象确实有很大不同时才有用。

我会选择前四个选项之一。

关于java - 忽略 jackson 属性(property),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37599844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com