如何仅从数组对象中获取url ?



我试图修改这个JSON删除键值除了"url"从附件的数组对象。

Json路径版本:2.7.0

{
"fields": {
"item_name": "mypassn",
"id": "nopass cell",
"Attachment": [
{
"id": "attaMKW4RR5misdsD",
"url": "https://url1.com",
"filename": "test-nopass.txt",
"size": 17,
"type": "text/plain"
},
{
"id": "attHy3s6MBzce7Qoq",
"url": "https://url2.com",
"filename": "test-mypass.txt",
"size": 28,
"type": "text/plain"
},
{
"id": "atth4oFqzanlk9532",
"url": "https://url3.com",
"filename": "test- yourpass .txt",
"size": 28,
"type": "text/plain"
}
]
}
}

这里我想把这个json对象修改成下面的代码。

{
"fields": {
"item_name": "mypassn",
"id": "nopass cell",
"Attachment": [
{
"url": "https://url1.com",
},
{
"url": "https://url2.com",
},
{
"url": "https://url3.com",
}
]
}
}

那么我如何从Jayway JsonPath表达式实现这一点?

我不认为使用JsonPath可以实现。但是,这可以使用Jackson实现.

首先,在pom.xml中添加以下依赖项
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.3</version>
</dependency>

那么您可以尝试下面的代码。它应该工作

import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
...
public static void removeFieldsFromJson(String json) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json);
JsonNode fields = jsonNode.get("fields");
JsonNode attachments = fields.get("Attachment");

for (JsonNode attachment : attachments) {
((ObjectNode) attachment).remove("id");
((ObjectNode) attachment).remove("filename");
((ObjectNode) attachment).remove("size");
((ObjectNode) attachment).remove("type");
}

objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File("C:\test\payload.json"), jsonNode);
}

相关内容

  • 没有找到相关文章

最新更新