【问题标题】:How to correctly implement the spring java dto class?如何正确实现spring java dto类?
【发布时间】:2021-04-21 20:19:42
【问题描述】:

如何正确实现dto类,让拿到json的时候不用解析?

比如对于这样一个json对象:

{"errorCode":"0","errorMessage":"Success","actionCode":71015,
"actionCodeDescription":"Operation declined. ",
"amount":100000,"date":1618750705018,
"OrderParams":[{"name":"Finish","value":"false"}],
"attributes":[{"name":"number","value":"6a883ef0"}],
"cardInfo":{"pan":"111111**1111","expiration":"202202"},
"id":"123456","auth":"110101010"}

您需要从中获取键的值: actionCode , 金额, 日期 , pan

更新

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.Data;

@Data
public class OpenJsonFormat {
    
    @JsonProperty("actionCode")
    private String actionCode;
    
    @JsonProperty("amount")
    private String amount;
    
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
    private Date date;
 
    @JsonProperty("pan")
    private String pan;
  

}

【问题讨论】:

  • 对于那些名称与JSON字符串中对应字段名称相同的变量,您不需要添加@JsonProperty

标签: java json spring api dto


【解决方案1】:

使用 Spring 只需创建一个包含所有这些字段(以及相同名称的字段)的类,并将其用作控制器方法中的参数

即使 RequestBody 是可选的https://www.baeldung.com/spring-request-response-body,也喜欢这里

来自我的一个春季项目的示例(寻找发布方法):https://github.com/asgarov1/universitySchedule/blob/master/src/main/java/com/asgarov/university/schedule/controller/CourseController.java

【讨论】:

  • 导入 com.fasterxml.jackson.annotation.JsonProperty;导入 lombok.Data; @Data public class OpenJsonFormat { @JsonProperty("actionCode") private String actionCode; @JsonProperty("amount") 私有字符串金额; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss") 私人日期日期; @JsonProperty("pan") 私有字符串 pan; } 这样你能做到吗?
【解决方案2】:

只需创建两个类实体和 dto 类 像这样

这个实体类

    class EntityFoo{
        int id;
        string name;
        //create setter and getter  

// in this method translate from dto to entity

        public EntityFoo toEnity() {
            DtoFoo dto=new DtoFoo();
            dto.setId(this.id);
            dto.setName(this.name);
            return dto;
          }
    }

和 dto 类

    public DtoFoo(){
        int id;
        String name;
        //create geeter and setter

// in this method translate from entity to dto
        public EntityFoo toDto() {
            EntityFoo entity =new DtoFoo();
            entity.setId(this.id);
            entity.setName(this.name);
            return entity;
        }
    
    }

这是 github 中的链接,我使用 dto 和实体 https://github.com/abdalrhmanAlkraien/Spring-Book-Repo

或者您可以使用 mapstruct 接口将 dto 转换为实体或将实体转换为 dto

【讨论】:

  • 格式良好的代码更易于阅读。请帮助其他人阅读您的代码:)
  • 例如显示新的编辑,并在 post 方法采用 dto 参数并转换为实体时将此类用于服务,当 get 方法采用实体参数并转换为 dto 并将此项目检查到我使用的 get hub 时dto 和实体github.com/abdalrhmanAlkraien/Spring-Book-Repo
猜你喜欢
  • 1970-01-01
  • 2020-06-22
  • 1970-01-01
  • 2023-01-24
  • 2013-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
相关资源
最近更新 更多