是的,您可以使用 ObjectMapper 的 readerForUpdating 方法创建一个 ObjectReader,它将从根 JSON 对象更新现有实例,而不是实例化一个新实例:
@Test
public void apply_json_to_existing_object() throws Exception {
ExampleRecord record = new ExampleRecord();
ObjectReader reader = mapper.readerForUpdating(record)
.with(JsonParser.Feature.ALLOW_SINGLE_QUOTES)
.with(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
reader.readValue("{ firstProperty: 'foo' }");
reader.readValue("{ secondProperty: 'bar' }");
assertThat(record.firstProperty, equalTo("foo"));
assertThat(record.secondProperty, equalTo("bar"));
}
public static class ExampleRecord {
public String firstProperty;
public String secondProperty;
}
您还可以从现有的ObjectReader 创建一个价值更新阅读器。以下声明似乎等效:
ObjectReader reader = mapper.reader(ExampleRecord.class)
.withValueToUpdate(record)
.with(/* features etc */);
加法
不过,以上内容并没有真正回答您的问题。
由于您没有想要以 JSON 形式对记录进行更改,而是以地图形式进行更改,因此您必须进行一些修改,以便杰克逊能够读取您的地图。您不能直接执行此操作,但您可以将“JSON”写入令牌缓冲区,然后将其读回:
@Test
public void apply_map_to_existing_object_via_json() throws Exception {
ExampleRecord record = new ExampleRecord();
Map<String, Object> properties = ImmutableMap.of("firstProperty", "foo", "secondProperty", "bar");
TokenBuffer buffer = new TokenBuffer(mapper, false);
mapper.writeValue(buffer, properties);
mapper.readerForUpdating(record).readValue(buffer.asParser());
assertThat(record.firstProperty, equalTo("foo"));
assertThat(record.secondProperty, equalTo("bar"));
}
(顺便说一句,如果这看起来很费力,序列化到令牌缓冲区并再次反序列化实际上是 ObjectMapper.convertValue 的实现方式,因此功能上的变化并不大)