Search code examples
jsonjakarta-eeresteasywildflypojo

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


I have JSON

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

and Java POJO

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

  //constructor, getters, setters
}

POST method:

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

This is work nice when POST or PUT request are coming and JSON is parsed to POJO, but when

"friends": null

WildFly RestEasy cannot parse JSON to POJO and Response with error is returned

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

Does anybody knows how to fix this with some annotation or additional setup?


Solution

  • Problem was in setter method

    Before fix:

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

    To fix just need to add validation

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

    Hopefully this will help to avoid same mistakes for others.