返回枚举名称和字符串值作为api响应

时间:2020-05-03 06:16:54

标签: java spring-boot rest jpa enums

这是我的枚举类

public enum Status {
    OPEN("Open"),
    IN_PROCESS("In Process"),
    ON_HOLD("On Hold"),
    RESOLVED("Resolved");

    private String status;

    Status(String status) {
        this.status = status;
    }

    @JsonValue
    public String getStatus() {
        return status;
    }
}

我的api当前以字符串形式返回Status的值,这是返回的json响应的一部分。 {"id":1,"name":"John","subject":"Help","status":"Open"}

我如何做出类似{"status": {"id": "ON_HOLD", "value": "On Hold"}}

的回复

这是使用枚举状态的模型,省略了某些部分。

public class Ticket {
    private @Id @GeneratedValue(strategy=GenerationType.IDENTITY) Long id;
    private String name;
    private String subject;

    @Enumerated(EnumType.STRING)
    private Status status;

    //getters, setters, etc.
}

我的TicketController

@RestController
public class TicketController {
    private final TicketRepository repository;
    private final TicketResourceAssembler assembler;

    TicketController(TicketRepository repository, TicketResourceAssembler assembler) {
        this.repository = repository;
        this.assembler = assembler;
    }

    @GetMapping("/tickets/{id}")
    public EntityModel<Ticket> one(@PathVariable Long id) {

        Ticket ticket = repository.findById(id).orElseThrow(() -> new EntityNotFoundException(Ticket.class, "id", id.toString()));
        return assembler.toModel(ticket);
    }
}

汇编器

@Component
public class TicketResourceAssembler implements RepresentationModelAssembler<Ticket, EntityModel<Ticket>> {
    @Override
    public EntityModel<Ticket> toModel(Ticket ticket) {

        EntityModel<Ticket> ticketResource = new EntityModel<>(ticket,
            linkTo(methodOn(TicketController.class).one(ticket.getId())).withSelfRel(),
            linkTo(methodOn(TicketController.class).all()).withRel("tickets"));

        return  ticketResource;
    }
}

存储库只是扩展到JpaRepository的接口。

2 个答案:

答案 0 :(得分:1)

您需要添加getName()方法枚举类:

public enum Status {
        OPEN("Open"),
        IN_PROCESS("In Process"),
        ON_HOLD("On Hold"),
        RESOLVED("Resolved");

        private String status;

        Status(String status) {
            this.status = status;
        }

        public String getName() {
            return this.name();
        }

        @JsonValue
        public String getStatus() {
            return status;
        }
    }

现在,您需要添加@JsonGetter方法以获取Ticket类中的状态:

@JsonGetter
    public JsonNode getStatus() {
        return JsonNodeFactory.instance.objectNode().put("id",status.getName()).put("value",status.getValue());
    }

答案 1 :(得分:0)

我建议的一个不错的解决方案是使用 @JsonProperty

public enum Status {

    @JsonProperty("LORA/TRACK_RFID")
    IN_PROCESS("In Process");
}

通过使用此注释,我们只是告诉 Jackson 将 @JsonProperty 的值映射到使用此值注释的对象。

作为上述声明的结果,将有字符串:"In Process"