Home > Net >  Convert ENUM to DTO
Convert ENUM to DTO

Time:10-27

I have this Java ENUM which I would like to convert to DTO:

public enum TicketStatus {
    N("new", "New"),
    A("assigned", "Assigned"),
    IP("in_progress", "In-progress"),
    C("closed", "Closed");

    private String shortName;

    private String fullName;

    TicketStatus(String shortName, String fullName) {
        this.shortName = shortName;
        this.fullName = fullName;
    }

    @JsonValue
    public String getShortName() {
        return shortName;
    }

    @JsonValue
    public String getFullName() {
        return fullName;
    }
}

I want to convert the EMUM to a list of items:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
public class TicketStatusTypesDTO {

    private String code;

    private String name;
}

code should be mapped as shortName and name as fullName. How this can be converted?

EDIT:

I tried this:

List<TicketStatusTypesDTO> list = null;
for (TicketStatus status : TicketStatus.values()) {
   list.add(new TicketStatusTypesDTO(status.getShortName(), status.getShortName()));
}

How I can improve the code by using stream? Something like this:

TicketStatus.values().entrySet().stream()
            .map(g -> new TicketStatusTypesDTO(g.getKey(), g.getValue())).collect(Collectors.toList());

CodePudding user response:

You can use @JsonProperty for that.

    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder(toBuilder = true)
    public class TicketStatusTypesDTO {    
        @JsonProperty("shortName")
        private String code;
    
        @JsonProperty("fullName")
        private String name;
    }

You could also do the mapping with the constructor like so:

@JsonCreator
public TicketStatusTypesDTO (
  @JsonProperty("shortName") String code, 
  @JsonProperty("fullName") String name) {
    this.code = code;
    this.name = name;
}

More on this here: https://www.baeldung.com/jackson-annotations

  •  Tags:  
  • java
  • Related