json—如何正确实现SpringJavaDTO类?

ztmd8pv5  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(457)

如何正确实现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、amount、date、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;

}
tgabmvqs

tgabmvqs1#

只需像这样创建两个类实体和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中的链接,我用它来表示数据和实体https://github.com/abdalrhmanalkraien/spring-book-repo
或者可以使用mapstruct接口将dto转换为实体或实体转换为dto

3hvapo4f

3hvapo4f2#

使用spring,只需创建一个包含所有这些字段(以及字段的相同名称)的类,并将其用作控制器方法中的参数
就像这里,尽管requestbody是可选的https://www.baeldung.com/spring-request-response-body
我的一个spring项目的示例(寻找post方法):https://github.com/asgarov1/universityschedule/blob/master/src/main/java/com/asgarov/university/schedule/controller/coursecontroller.java

相关问题