简体   繁体   English

在控制器中返回 DTO

[英]Return DTOs in the controller

I have an Operation service that has a list function that returns a list of OperationDTO however when the controller calls this function the list returns null dto objects and if I change the type of return in the service to Operation entity type the controller works fine我有一个操作服务,它有一个返回 OperationDTO 列表的列表函数,但是当控制器调用此函数时,列表返回空 dto 对象,如果我将服务中的返回类型更改为操作实体类型,控制器工作正常

public class OperationDTO {

private Long user_id;
private Long account_id;
private int amount;
private TypeOperation typeOperation;
private boolean status;
private Date created;
private Date updated;


public OperationDTO(Operation operation){
      this.user_id = operation.getUser().getId();
     this.account_id = operation.getAccount().getId();
     this.amount = operation.getAmount();
     this.typeOperation = operation.getTypeOperation();
     this.status = operation.isStatus();
     this.created = operation.getCreated();
     this.updated = operation.getUpdated();

}
public OperationDTO(){}

@Override
public String toString() {
    return this.user_id + " "+
            this.account_id + " "+
            this.typeOperation + " "+
            this.amount+ " "+
            this.status+ " "+
            this.created+ " "+
            this.updated
            ;
  }
}

this is my implementation to my service这是我对我的服务的实现

    public Collection<OperationDTO> listOperation() {
    Collection<Operation> operations = (Collection<Operation>) 
     operationRepository.findAll();
      Collection<OperationDTO> operationDTOS = new ArrayList<>();
      for (Operation oper: operations){
         OperationDTO op = new OperationDTO(oper);
        operationDTOS.add(op);
      }
      System.out.println("Les operations " + operationDTOS);
      return operationDTOS;
}

My controller我的控制器

    public ResponseEntity<EntityResponse> list(){
    return  ResponseEntity.ok(
            EntityResponse.builder()
                    .timeStamp(LocalDateTime.now())
                    .message("List of Operations" )
                    .status(HttpStatus.OK)
                    .statusCode(HttpStatus.OK.value())
                    .data(Map.of("Operation list", operationService.listOperation()))
                    .build()
    );
}

When a call this list in my controller with postman I have this response当用邮递员在我的控制器中调用这个列表时,我有这个响应

{
"timeStamp": [
    2022,
    5,
    13,
    20,
    46,
    57,
    754770000
],
"statusCode": 200,
"status": "OK",
"message": "List of Operations",
"data": {
    "Operation list": [
        {},
        {},
        {}
    ]
}

} }

please need some help请需要一些帮助

As the existing comments already stated, your OperationDTO does not provide any means of access from outside, without changes everything is just private .正如现有评论已经指出的那样,您的 OperationDTO 不提供任何来自外部的访问方式,无需更改,一切都是private

You can either annotate the fields that you want in your response with @JsonProperty from Jackson or you can provide public getter methods, for example with Lombok.您可以使用来自 Jackson 的@JsonProperty在响应中注释您想要的字段,也可以提供公共 getter 方法,例如使用 Lombok。 The same goes for TypeOperation. TypeOperation 也是如此。

With JsonProperty:使用 JsonProperty:

public class OperationDTO {
  @JsonProperty("userId") // you can rename it here to camel-case, if you like
  private Long user_id;
  ...
}

With Lombok:与龙目岛:

@Getter
public class OperationDTO {
  private Long user_id;
  ...
}

Witout annotations:没有注释:

public class OperationDTO {
  private Long user_id;
  ...
  private Long getUserId() {
    return user_id;
  }
}

Notice that in the last case your value will be serialized by getter name, so you will see "userId": 1234534 in the JSON, not UserId nor user_id .请注意,在最后一种情况下,您的值将通过 getter 名称进行序列化,因此您将在 JSON 中看到"userId": 1234534 ,而不是UserIduser_id

To get rid of boilerplate code, you can also combine both @JsonProperty and @Getter for the best of both worlds.要摆脱样板代码,您还可以结合使用@JsonProperty@Getter以获得两全其美的效果。 When you use Lombok for the first time, please read how to set up the annotation processing in your IDE.当您第一次使用 Lombok 时,请阅读如何在您的 IDE 中设置注释处理。

Also note that this answer only provides hints on serialization, if you ever want to read a JSON, there are also other things missing which I won't cover here.另请注意,此答案仅提供有关序列化的提示,如果您想阅读 JSON,还缺少其他内容,我不会在这里介绍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM