Home > Mobile >  ObjectMapper converting array into set of Objects with one field
ObjectMapper converting array into set of Objects with one field

Time:02-04

I have TestEntity class:

@Data
public class TestEntity {

    @NotEmpty(message = "strings are required")
    private Set<InnerTestEntity> strings;

}

Also I have InnerTestEntity:

@Data
public class InnerTestEntity {

    @NotEmpty(message = "name is required")
    private String name;

}

And I have JSON file:

{
  "strings" : [
    "name1",
    "name2",
    "name3"
  ]
}

The idea is to map each name from Strings into InnerTestEntity objects to "name" field, and have TestEntity object with this set of InnerTestEntity objects.

When I call this:

TestEntity test = objectMapper.readValue(*Path to JSON*, new TypeReference<>() {
        });

It gives me this error:

Cannot construct instance of ...InnerTestEntity (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('name1')

What is the option to map it properly?

CodePudding user response:

In your class InnerTestEntity use @JsonValue annotation:

@Data
public class InnerTestEntity {

    @NotEmpty(message = "name is required")
    @JsonValue //This is the added line
    private String name;

}

See Javadoc for @JsonValue

  •  Tags:  
  • Related