如何使用 WildFly RestEasy 将具有可为空数组属性的 JSON 映射到 POJO

How to map JSON with nullable array properties to POJO using WildFly RestEasy

我有JSON

{
  "name": "volo",
  "friends": ["joe", "alex"]
}

和JavaPOJO

class Person {
  private String name;
  private Set<String> friends;

  //constructor, getters, setters
}

POST方法:

@POST
@Consumes("application/json")
public Response createPerson(Person person) {
  //logic
}

当 POST 或 PUT 请求到来并且 JSON 被解析为 POJO 时,这很好用,但是当

"friends": null

WildFly RestEasy 无法将 JSON 解析为 POJO 并返回错误响应

com.fasterxml.jackson.databind.JsonMappingException: N/A (through reference chain: dk.systematic.beacon.workspace.WorkspaceInfo["friends"])

有人知道如何通过一些注释或其他设置来解决这个问题吗?

问题出在 setter 方法中

修正前:

public void setFriends(Set<String> friends) {
  this.friends = new HashSet<>(friends)
}

修复只需要添加验证

public void setFriends(Set<String> friends) {
  if (friends != null) {
    this.friends = new HashSet<>(friends)
  }
}

希望这有助于避免其他人犯同样的错误。