首页 > 解决方案 > Servlet 调用返回错误的 json 字符串,因为通过 ResponseEntity 对象使用了错误的构造函数

问题描述

我的配置:Spring 4 Jackson 2.9 Angular 8

我有一个带有两个构造函数的 pojo:

public Notification(int code, String message, List<T> objets) {
    this.code = code;
    this.message = message;
    this.objets = objets;
}   

public Notification(int code, String message, T objet) {
    this.code = code;
    this.message = message;
    this.objet = objet;
}

这个 pojo 的目的是在请求的结果中添加一个内部代码和一个字符串消息,请求可以产生一个对象或一个对象列表(或者根本没有对象,但我不想编写每个构造函数以上)。

我的问题是,当我的查询结果是一个列表时,我认为我正在使用带有对象列表的构造函数。但是,我的浏览器终端中的查询响应是一个空对象。所以我想使用第二个构造函数。

为什么不使用我的第一个构造函数?

这是我的存储库:

public Notification<Prelevement> findActiveTransferts(int id){
    LocalDateTime currentTime = LocalDateTime.now();
    Date date =   java.sql.Date.valueOf(currentTime.toLocalDate());
    String sql = "from Prelevement pre where :date between pre.dateDebut and pre.dateFin and pre.compte =:idCompte";

    try {
        Compte acc = (Compte)this.getCurrentSession().createQuery("from Compte acc where acc.id =:id").setParameter("id", id).getSingleResult();
        List<Prelevement> list = (List<Prelevement>) this.getCurrentSession().createQuery(sql).setParameter("date", date).setParameter("idCompte", acc).getResultList();
        return new Notification<Prelevement>(Notification.OPERATION_SUCCESSFUL, "Nous avons trouvé "+list.size()+" éléments correspondants à votre recherche", list);
    }catch(NoResultException nre) {
        return new Notification<Prelevement>(Notification.DB_NO_DATA_FOUND, "Nous avons trouvé aucun élément correspondant à votre recherche");
    }       
}

和我的 RestController :

@PostMapping("/pre/get")
public ResponseEntity<Notification<Prelevement>> get(@RequestBody DTOAcc dto){

    Notification<Prelevement> result = ((PrelevementRepository)repository).findActiveTransferts(dto.getId());
    System.out.println(result);
    return new ResponseEntity<Notification<Prelevement>>(result, HttpStatus.OK);
}

我希望浏览器终端中的 json 字符串是对象列表,而不是预期列表时的对象。

结果 json 字符串为:{"code":0,"message":"Nous avons trouvé 1 éléments associateants à votre recherche","objet":null}

并且应该是: {"code":0,"message":"Nous avons trouvé 1 éléments associateants à votre recherche","objets":[ {"id":"0", ... other attributes} ]}

Spring发送给浏览器的对象的toString方法如下Notification [code=0, message=Nous avons trouvé 1 éléments associateantsà votre recherche, objets=[pro.logikal.comptes.entity.Prelevement@16b51ef6]] 所以我们可以看到我的请求找到了一个对象列表(准确地说是一个对象的列表)。

你能给我指路吗?

标签: springconstructor

解决方案


发现我的错误,我没有为此列表生成任何 getter 或 setter。构造函数导致不可见,因此它进入了下一个构造函数。


推荐阅读