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

huangapple go评论89阅读模式
英文:

Returning both enum name and string value as api response

问题

这是我的枚举类:

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, 等等
}

我的 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;
    }
}

Repository 只是一个继承自 JpaRepository 的接口。

英文:

This is my enum class

public enum Status {
	OPEN(&quot;Open&quot;),
	IN_PROCESS(&quot;In Process&quot;),
	ON_HOLD(&quot;On Hold&quot;),
	RESOLVED(&quot;Resolved&quot;);
	
	private String status;
	
	Status(String status) {
		this.status = status;
	}

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

My api is currently returning the value of Status as a string, here's a part of the json response returned. {&quot;id&quot;:1,&quot;name&quot;:&quot;John&quot;,&quot;subject&quot;:&quot;Help&quot;,&quot;status&quot;:&quot;Open&quot;}

How do i make my response something like {&quot;status&quot;: {&quot;id&quot;: &quot;ON_HOLD&quot;, &quot;value&quot;: &quot;On Hold&quot;}}

This is the model using the enum status, some parts omitted.

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.
}

My 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(&quot;/tickets/{id}&quot;)
    public EntityModel&lt;Ticket&gt; one(@PathVariable Long id) {

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

The assembler

@Component
public class TicketResourceAssembler implements RepresentationModelAssembler&lt;Ticket, EntityModel&lt;Ticket&gt;&gt; {
	@Override
    public EntityModel&lt;Ticket&gt; toModel(Ticket ticket) {
		
		EntityModel&lt;Ticket&gt; ticketResource = new EntityModel&lt;&gt;(ticket,
			linkTo(methodOn(TicketController.class).one(ticket.getId())).withSelfRel(),
			linkTo(methodOn(TicketController.class).all()).withRel(&quot;tickets&quot;));
		
        return  ticketResource;
    }
}

The repository is just an interface that extends to JpaRepository.

答案1

得分: 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;
    }
}

然后,在 Ticket 类中添加 @JsonGetter 方法用于获取状态:

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

You need to add getName() method enum class:

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

        private String status;

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

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

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

Now you need to add @JsonGetter method for status in Ticket class:

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

答案2

得分: 0

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

public enum Status {

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

通过使用这个注解,我们只需告诉Jackson将@JsonProperty的值映射到带有此值注释的对象。

由于上述声明的结果,将得到字符串:"In Process"

英文:

A nice solution I suggest is using @JsonProperty.

public enum Status {

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

By using this annotation, we are simply telling Jackson to map the value of the @JsonProperty to the object annotated with this value.

As a result of the above declaration, will have the string: &quot;In Process&quot;

huangapple
  • 本文由 发表于 2020年5月3日 14:16:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/61570375.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定