gpt4 book ai didi

java - Jackson 可以用于更新 POJO 吗?

转载 作者:行者123 更新时间:2023-12-04 12:21:45 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Merging Two JSON Documents Using Jackson

(6 个回答)


2个月前关闭。




从 JSON 转换为 Java 对象的最通用方法是将 JSON 捕获为 Map<String, Object> .从此(或直接)我可以轻松转换为 POJO:

User user = objectMapper.convertValue(jsonMap, User.class);
任意 User原始 JSON 中不存在的字段将设置为其默认值。虽然这对于创建新对象非常有用(响应(比如)API 调用),但它不适用于更新 POJO。
我想要实现的是更新现有的 User使用 Jackson 从传入的 JSON 中获取对象。这意味着:
  • 传入 JSON 中的属性(也是 POJO 中的字段)用于更新(覆盖)POJO 中的相应字段。
  • 传入 JSON 中的属性是 不是 POJO 中的字段被忽略。
  • User 中的字段在传入的 JSON 中没有任何相应属性的 POJO 被保留下来。

  • 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.


    然后使用 readValue ObjectReader :

    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);

    关于java - Jackson 可以用于更新 POJO 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68772565/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com