java - 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"
}
]
}
解决方案
推荐阅读
- javascript - 在 gojs 图表中格式化和对齐文本
- html - 使用 Sass CSS 和 FlexBox 垂直堆叠转换后的文本
- python - 使用python的windows和mac应用程序
- c# - JSON Web 令牌 - 如何识别用户?
- ruby-on-rails - 在 Active Admin Rails 中创建新项目时过滤下拉列表
- applescript - 使用 applescript 清除 ITerm2 缓冲区
- appcelerator - 容器视图中的 Appcelerator 菜单
- java - 如何从覆盖方法java调用值?
- java - 在具有身份验证的代理后面使用 Azure EventHub
- python - 在 Django StaticLiveServerTestCase 中提交使用 Intercooler 的表单