Search code examples
setjackson

Jackson: Deserializing a Set?


When I attempt to deserialize:

{
  "tags": {}
}

into:

public static class Foo
{
    private final Set<URI> tags;

    /**
     * Creates a new Foo entity.
     * <p/>
     * @param tags the room tags
     * @throws NullPointerException if tags is null
     */
    @JsonCreator
    public Foo(@JsonProperty("tags") Set<URI> tags)
    {
        Preconditions.checkNotNull(tags, "tags may not be null");

        this.tags = ImmutableSet.copyOf(tags);
    }

    /**
     * @return the tags
     */
    public Set<URI> getTags()
    {
        return tags;
    }
}

I get:

org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.HashSet out of START_OBJECT token
 at [line: 1, column: 2]

Shouldn't this work out-of-the-box?


Solution

  • For this to work, you need to convert to an array:

    {
      "tags": []
    }
    

    If not, how would you represent multiple elements in the tags set using valid JSON?