首页 > 解决方案 > Java jackson - 更新 json 中的数组

问题描述

我是java杰克逊的新手。我想解析一个 json 字符串,并通过复制数组值的相同内容,用大小为 2 的数组替换其中的一个数组(其大小为 1)。例如:输入 json 文件

{
  "order_info": {
    "order_number": "123456",
    "order_date": "2019-11-08T10:23:29.502Z",
    "attributes": {
      "checkout_locale": "en_US"
    },
    "order_items": [
      {
        "categories": [
          "Clothing"
        ],
        "is_backordered": false,
        "vendors": [
          {
            "name": "zxcx"
          }
        ],
        "discount_amount": 0,
        "final_sale_date": "2019-03-01T20:07:16Z"
      }
    ]
  }
}

需要输出json:

{
  "order_info": {
    "order_number": "123456",
    "order_date": "2019-11-08T10:23:29.502Z",
    "attributes": {
      "checkout_locale": "en_US"
    },
    "order_items": [
      {
        "categories": [
          "Clothing"
        ],
        "is_backordered": false,
        "vendors": [
          {
            "name": "zxcx"
          }
        ],
        "discount_amount": 0,
        "final_sale_date": "2019-03-01T20:07:16Z"
      },
      {
        "categories": [
          "Clothing"
        ],
        "is_backordered": false,
        "vendors": [
          {
            "name": "zxcx"
          }
        ],
        "discount_amount": 0,
        "final_sale_date": "2019-03-01T20:07:16Z"
      }
    ]
  }
}

我尝试了如下代码:

   ObjectNode objectNode = (ObjectNode) mapper.readTree(ordersApiBasePayload);
   ArrayNode nodeArray = (ArrayNode) jsonNode.get("order_info").get("order_items");
   ArrayNode items = objectNode.putArray("order_items");
   items.add(nodeArray.get(0));
   items.add(nodeArray.get(0));

但是,通过这种方式,我不会将现有的 order_items 替换为新的两个 order_items。我在 json 末尾附加了两个新的 order_items,如下所示:

{
  "order_info": {
    "order_number": "123456",
    "order_date": "2019-11-08T10:23:29.502Z",
    "attributes": {
      "checkout_locale": "en_US"
    },
    "order_items": [
      {
        "categories": [
          "Clothing"
        ],
        "is_backordered": false,
        "vendors": [
          {
            "name": "zxcx"
          }
        ],
        "discount_amount": 0,
        "final_sale_date": "2019-03-01T20:07:16Z"
      }
    ]
  },
  "order_items": [
    {
      "categories": [
        "Clothing"
      ],
      "is_backordered": false,
      "vendors": [
        {
          "name": "zxcx"
        }
      ],
      "discount_amount": 0,
      "final_sale_date": "2019-03-01T20:07:16Z"
    },
    {
      "categories": [
        "Clothing"
      ],
      "is_backordered": false,
      "vendors": [
        {
          "name": "zxcx"
        }
      ],
      "discount_amount": 0,
      "final_sale_date": "2019-03-01T20:07:16Z"
    }
  ]
}

标签: javajsonjackson-databind

解决方案


推荐阅读