【问题标题】:Update JsonNode with new object values用新的对象值更新 JsonNode
【发布时间】:2021-12-30 19:27:43
【问题描述】:

我得到 JsonNode,其中一个键的值为空。需要用对象更新这个值。

m 返回的值如下,其中 notes 为空,需要更新该 notes 值。

{
 "a":"aaaaaa",
 "b":"bbbbbb",
 "notes":null,
}

代码尝试将 m 作为 JsonNode 来:

return seasonsAdapter.callSeasonsJsonAPI(seasonId, hunterId, uuid).map(m -> {
String notes=AppJsonUtil.getJsonAsString(seasonsNotesDto);
ObjectNode objectNode = (ObjectNode) m;
ObjectNode objectNode1=objectNode.put("notes", notes);
objectNode1.put("notesText", seasonsNotesDto.getNotesText());
objectNode1.put("notesTime", seasonsNotesDto.getNotesTime());
objectNode1.put("notesTitle", seasonsNotesDto.getNotesTitle());
return m;
});

结果:

  {
   "a":"aaaaaa",
   "b":"bbbbbb",
  "notes": "{\"notesText\":\"this is my new note 1 \",\"notesTitle\":\"new note 1 Title\",\"notesTime\":1640865242125}",

    "notesText": "this is my new note 1 ",

    "notesTime": 1640865242125,

    "notesTitle": "new note 1 Title"
   }

预期:

  {
   "a":"aaaaaa",
   "b":"bbbbbb",
  "notes": {
           "notesText": "this is my new note 1 ",
            "notesTime": 1640865242125,
            "notesTitle": "new note 1 Title"
           }
   }

【问题讨论】:

  • 放弃你的notes String。而是创建一个ObjectNode,将字段添加到其中,然后将其添加到objectNode1。或者,查看您的AppJsonUtil 是否具有将对象直接转换为ObjectNode 的机制。

标签: java json jackson jackson-databind


【解决方案1】:

我已经弄清楚需要做什么。检查下面的代码

ObjectMapper mapper = new ObjectMapper();
    ObjectNode obj = (ObjectNode) m;
    if (seasonsNotesDto!=null)
    {
        ObjectNode notes = mapper.createObjectNode();
        notes.put("notesTitle", seasonsNotesDto.getNotesTitle());   
        notes.put("notesText", seasonsNotesDto.getNotesText()); 
        notes.put("notesTime", seasonsNotesDto.getNotesTime()); 
        obj.set("notes", notes);
    }
    return m;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 2021-11-27
    • 2021-07-08
    • 2021-11-07
    相关资源
    最近更新 更多