忽略杰克逊的财产

时间:2016-06-02 18:44:31

标签: java json jackson

{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
      }
    }

归还了以下内容。我想要杰克逊todo是无视老师。我不太关心这个电话的教师用品。问题是我不想访问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;
        }

    }

2 个答案:

答案 0 :(得分:1)

您有多种选择:

  1. @JsonIgnoreProperties放在StudentEntity课程上。请参阅:http://static.javadoc.io/com.fasterxml.jackson.core/jackson-annotations/2.7.4/com/fasterxml/jackson/annotation/JsonIgnoreProperties.html

  2. JsonSerializer撰写自定义StudentEntity。在这里,您必须记下构造输出JSON的每个字段的代码。请参阅:http://www.baeldung.com/jackson-custom-serialization

  3. 使用Mixin,它基本上是一个与您的StudentEntity匹配的界面。您可以在@JsonIgnore方法上使用getTeacher()。请参阅:http://wiki.fasterxml.com/JacksonMixInAnnotations

  4. @JsonSerialize课程中的idGroup媒体资源上添加StudentEntity。注释将类作为实现JsonSerializer的参数。虽然您可以指定一种方法来序列化idGroup属性,如果(且仅当)杰克逊序列化StudentEntity的实例。 (这或多或少就像选项2. ,但要实现起来要简单得多)

  5. 编写与您的输出格式匹配的DTO类。然后将字段从StudentEntity对象复制到StudentEntityDTO对象(没有teacher属性),然后让Jackson序列化DTO对象而不是原始{ {1}}对象。这是很多要编写的代码,只有在输出JSON与原始对象非常不同时才有用。

  6. 我选择前四个选项中的一个。

答案 1 :(得分:0)

把@JsonIgnore放在老师的吸气器上,它不会出来放json