我可以在我的休息控制器上请求有效负载,例如
{
"id" : "dffds-fsdf-dfdf-dsf",
"name" : "toto",
"age" : "18"
}
但正文参数 id 不是必需的,可能为空。在这种情况下,我需要生成一个 ID(使用 UUID 或其他任何东西)
有没有办法使用注释来做到这一点,例如?
一种方法是将默认值分配给变量,因此如果正文参数 id 为 null,则将分配此默认值,但如果在正文中传递 id,则不会分配此默认值。
public class Model {
private String name;
private String id=UUID.randomUUID().toString();
private int age;
}
我们必须至少解决两种情况:
id
字段作为null
发送,例如{ "id": null, ... }
- 有效载荷中不存在
id
字段,例如{ "name" : "toto", "age" : "18" }
似乎没有可以产生这种行为的注释,但以下有效负载映射类应该可以解决问题:
import java.util.UUID;
public class Payload {
private String id = UUID.randomUUID().toString();
private String name;
private String age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id != null ? id : UUID.randomUUID().toString();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
/* You can safely remove this method, it's here only for test purposes. */
public static void main(String... args) throws java.io.IOException {
String[] tests = new String[] {
"{ "id": "dffds-fsdf-dfdf-dsf", "name": "toto", "age": "18" }",
"{ "name": "toto", "age": "18" }",
"{ "age": "18" }",
"{ "id": null, "name": "toto", "age": "18" }",
"{ "id": null, "age": "18" }",
"{ "id": null, "name": "toto" }",
"{ "id": null }",
"{ }"
};
for (String it : tests) {
Payload payload = new com.fasterxml.jackson.databind.ObjectMapper().readValue(it, Payload.class);
System.out.println(it + " => [id=" + payload.getId() + ", name=" + payload.getName() + ", age=" + payload.getAge() + "]");
}
}
}
如果运行main
方法,将获得如下所示的输出,该输出应满足你的要求:
{ "id": "dffds-fsdf-dfdf-dsf", "name": "toto", "age": "18" } => [id=dffds-fsdf-dfdf-dsf, name=toto, age=18]
{ "name": "toto", "age": "18" } => [id=f3218a7c-6e2c-47fc-93b9-746ceec7b56b, name=toto, age=18]
{ "age": "18" } => [id=21899f52-d273-4c89-8a16-26871f4ec351, name=null, age=18]
{ "id": null, "name": "toto", "age": "18" } => [id=0a2ba8f6-cee3-44f0-89a6-e18ac55346d2, name=toto, age=18]
{ "id": null, "age": "18" } => [id=4f8125eb-ec68-4343-a04f-1490ffb81a76, name=null, age=18]
{ "id": null, "name": "toto" } => [id=b5d59feb-5730-4929-bc41-b0f17da68a39, name=toto, age=null]
{ "id": null } => [id=ccb9b192-daa3-4877-b232-56ec483b9d8e, name=null, age=null]
{ } => [id=d56cc66c-f9af-4dea-8ad4-86c16c9921a7, name=null, age=null]