首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Spring rest产生重复的json

Spring rest产生重复的json
EN

Stack Overflow用户
提问于 2016-02-15 23:01:36
回答 2查看 3.6K关注 0票数 2

我有一个简单的问答应用程序,我正在试验,它有三个类别的测验,问题和答案。基本关系如下:

@Entity
public class Quiz {

    @Id
    @GeneratedValue

    private Long id; 

    private String description;

     @OneToMany(cascade=CascadeType.PERSIST, fetch=FetchType.EAGER)
     private List<Question> questions = new ArrayList<>();

@Entity
public class Question {

    @Id
    @GeneratedValue

    private Long id;

    private String description;

    @ElementCollection(fetch=FetchType.EAGER)
    private List<Answer> answers;

@Embeddable
public class Answer {


    private String description;
    private boolean correct;

JPA/数据库通过包含一个问题和三个答案的单个测验正确加载。但是,返回的相应JSON有很多重复数据。

{
  "id" : 1,
  "description" : "Intro to Spring 4",
  "questions" : [ {
    "id" : 1,
    "description" : "What is Spring?",
    "answers" : [ {
      "description" : "A season",
      "correct" : false
    }, {
      "description" : "A coily wire",
      "correct" : false
    }, {
      "description" : "A wonderful framework",
      "correct" : true
    } ]
  }, {
    "id" : 1,
    "description" : "What is Spring?",
    "answers" : [ {
      "description" : "A season",
      "correct" : false
    }, {
      "description" : "A coily wire",
      "correct" : false
    }, {
      "description" : "A wonderful framework",
      "correct" : true
    } ]
  }, {
    "id" : 1,
    "description" : "What is Spring?",
    "answers" : [ {
      "description" : "A season",
      "correct" : false
    }, {
      "description" : "A coily wire",
      "correct" : false
    }, {
      "description" : "A wonderful framework",
      "correct" : true
    } ]
  } ]
}

有没有人看到什么明显的东西?我用的是Jackson mapper。

EN

回答 2

Stack Overflow用户

发布于 2018-09-11 02:56:54

在getter方法中注入@JsonProperty("yourFiledName")对我来说很有效。

@Entity
public class Quiz {

    @Id
    @GeneratedValue

    private Long id; 

    private String description;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
   @JsonProperty("description")
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

/**对问题实体类执行相同的操作**/

注:@JsonPropertiy来自Jackson库。对于maven用户,下面是依赖项

       <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.6</version>
        </dependency>
票数 1
EN

Stack Overflow用户

发布于 2019-01-30 00:08:40

只为那些在这个问题上苦苦挣扎的人。只需将@ElementCollection(fetch=FetchType.EAGER)设置为@ElementCollection(fetch=FetchType.LAZY)

这解决了我的问题!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35412605

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档