【发布时间】:2017-05-05 17:53:29
【问题描述】:
我正在使用 Jackson 2.8.5 和 ParameterNamesModule for Java 8 (https://github.com/FasterXML/jackson-modules-java8)。
当我想使用单个参数使用单个构造函数反序列化一个类时,我的问题非常具体。这是重现行为的测试:
public class JacksonTest {
@Test
public void TestReadValue() throws IOException {
ObjectMapper objectMapper = new ObjectMapper()
.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
.setVisibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.PUBLIC_ONLY)
.registerModule(new ParameterNamesModule(JsonCreator.Mode.PROPERTIES));
ImmutableIdentity identity = objectMapper.readValue("{\"id\":\"ABCDEF\"}", ImmutableIdentity.class);
assertEquals("ABCDEF", identity.id);
}
private static final class ImmutableIdentity {
private final String id;
public ImmutableIdentity(final String id) {
Objects.requireNonNull(id, "The id must not be null.");
this.id = id;
}
}
}
测试失败,原因如下:
com.fasterxml.jackson.databind.JsonMappingException: 无法构造 JacksonTest$ImmutableIdentity 的实例,问题:id 不能是 空值。在 [来源:{“id”:“ABCDEF”};行:1,列:15]
有趣的是,如果我在构造函数中添加另一个参数,测试就通过了。
public class JacksonTest {
@Test
public void TestReadValue() throws IOException {
ObjectMapper objectMapper = new ObjectMapper()
.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
.setVisibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.PUBLIC_ONLY)
.registerModule(new ParameterNamesModule(JsonCreator.Mode.PROPERTIES));
ImmutableIdentity identity = objectMapper.readValue("{\"id\":\"ABCDEF\"}", ImmutableIdentity.class);
assertEquals("ABCDEF", identity.id);
}
private static final class ImmutableIdentity {
private final String id;
public ImmutableIdentity(final String id, **final String unused**) {
Objects.requireNonNull(id, "The id must not be null.");
this.id = id;
}
}
}
我真的不喜欢在构造函数中使用无用的参数来减少歧义,因为它在我的业务对象中没有任何价值,特别是它们例如 ProjectId,或者一些定义我的抽象 Id实体,我也需要手动构建它们。所以我想找一个Jackson的配置来支持这个,但我做不到。
我还在这里为维护者交叉发布:https://github.com/FasterXML/jackson-modules-java8/issues/8
【问题讨论】: