Jackson 可以用来更新 POJO 吗?
Can Jackson be used to update a POJO?
从 JSON 转换为 Java 对象的最通用方法是将 JSON 捕获为 Map<String, Object>
。由此(或直接)我可以轻松地转换为 POJO:
User user = objectMapper.convertValue(jsonMap, User.class);
原始 JSON 中不存在的任何 User
字段都将设置为其默认值。虽然这对于创建 新对象(响应(比如)API 调用)非常有用,但它不适用于更新 一个POJO。
我想要实现的是使用 Jackson 更新 来自传入 JSON 的现有 User
对象。这意味着:
- 传入JSON中的属性(也是POJO中的字段)用于更新(覆盖)POJO中的相应字段。
- 传入 JSON 中 不是 POJO 字段的属性将被忽略。
User
POJO 中的字段在传入 JSON 中没有任何对应的属性。
Jackson 可以吗?
您可以使用 readerForUpdating
创建一个 ObjectReader
Factory method for constructing ObjectReader that will update given Object (usually Bean, but can be a Collection or Map as well, but NOT an array) with JSON data.
然后在ObjectReader
上使用readValue
:
Method that binds content read from given JSON string, using configuration of this reader. Value return is either newly constructed, or root value that was specified with withValueToUpdate(Object)
.
在类似于此的代码中:
ObjectReader objectReader = objectMapper.readerForUpdating(objectToUpdate);
MyType objectUpdated = objectReader.readValue(inputJson);
从 JSON 转换为 Java 对象的最通用方法是将 JSON 捕获为 Map<String, Object>
。由此(或直接)我可以轻松地转换为 POJO:
User user = objectMapper.convertValue(jsonMap, User.class);
原始 JSON 中不存在的任何 User
字段都将设置为其默认值。虽然这对于创建 新对象(响应(比如)API 调用)非常有用,但它不适用于更新 一个POJO。
我想要实现的是使用 Jackson 更新 来自传入 JSON 的现有 User
对象。这意味着:
- 传入JSON中的属性(也是POJO中的字段)用于更新(覆盖)POJO中的相应字段。
- 传入 JSON 中 不是 POJO 字段的属性将被忽略。
User
POJO 中的字段在传入 JSON 中没有任何对应的属性。
Jackson 可以吗?
您可以使用 readerForUpdating
创建一个 ObjectReader
Factory method for constructing ObjectReader that will update given Object (usually Bean, but can be a Collection or Map as well, but NOT an array) with JSON data.
然后在ObjectReader
上使用readValue
:
Method that binds content read from given JSON string, using configuration of this reader. Value return is either newly constructed, or root value that was specified with
withValueToUpdate(Object)
.
在类似于此的代码中:
ObjectReader objectReader = objectMapper.readerForUpdating(objectToUpdate);
MyType objectUpdated = objectReader.readValue(inputJson);