Gili
Gili

Reputation: 90111

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?

Upvotes: 1

Views: 12497

Answers (2)

ebaxt
ebaxt

Reputation: 8417

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?

Upvotes: 4

Igor Romcy
Igor Romcy

Reputation: 366

My problem was with mapping the payload, make sure that:

  • The fields are the same (payload and object) or you are using @JsonProperty correctly
  • You need to create setters on your object to framework fill the fields

I hope it helps

Upvotes: 0

Related Questions