ObjectMapper 将数组转换为具有一个字段的一组对象
ObjectMapper converting array into set of Objects with one field
我有 TestEntity class:
@Data
public class TestEntity {
@NotEmpty(message = "strings are required")
private Set<InnerTestEntity> strings;
}
我还有 InnerTestEntity:
@Data
public class InnerTestEntity {
@NotEmpty(message = "name is required")
private String name;
}
我有 JSON 个文件:
{
"strings" : [
"name1",
"name2",
"name3"
]
}
想法是将字符串中的每个名称映射到 InnerTestEntity 对象到“名称”字段,并使 TestEntity 对象具有这组 InnerTestEntity 对象。
当我这样调用时:
TestEntity test = objectMapper.readValue(*Path to JSON*, new TypeReference<>() {
});
它给我这个错误:
Cannot construct instance of ...InnerTestEntity
(although at least
one Creator exists): no String-argument constructor/factory method to
deserialize from String value ('name1')
正确映射的选项是什么?
在你的 class InnerTestEntity
中使用 @JsonValue
注释:
@Data
public class InnerTestEntity {
@NotEmpty(message = "name is required")
@JsonValue //This is the added line
private String name;
}
请参阅 @JsonValue
的 Javadoc
我有 TestEntity class:
@Data
public class TestEntity {
@NotEmpty(message = "strings are required")
private Set<InnerTestEntity> strings;
}
我还有 InnerTestEntity:
@Data
public class InnerTestEntity {
@NotEmpty(message = "name is required")
private String name;
}
我有 JSON 个文件:
{
"strings" : [
"name1",
"name2",
"name3"
]
}
想法是将字符串中的每个名称映射到 InnerTestEntity 对象到“名称”字段,并使 TestEntity 对象具有这组 InnerTestEntity 对象。
当我这样调用时:
TestEntity test = objectMapper.readValue(*Path to JSON*, new TypeReference<>() {
});
它给我这个错误:
Cannot construct instance of
...InnerTestEntity
(although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('name1')
正确映射的选项是什么?
在你的 class InnerTestEntity
中使用 @JsonValue
注释:
@Data
public class InnerTestEntity {
@NotEmpty(message = "name is required")
@JsonValue //This is the added line
private String name;
}
请参阅 @JsonValue
的 Javadoc