Java 在JSON响应中,如何在数组对象本身的数组之前添加名称?
我正在使用外部web服务并接收JSON响应。在这个响应中,有一个包含多个数组的对象实体,每个数组前面都有一个名称 我想在数组对象本身的数组之前添加名称 例如,这是原始响应:Java 在JSON响应中,如何在数组对象本身的数组之前添加名称?,java,json,Java,Json,我正在使用外部web服务并接收JSON响应。在这个响应中,有一个包含多个数组的对象实体,每个数组前面都有一个名称 我想在数组对象本身的数组之前添加名称 例如,这是原始响应: { "entities": { "entity": [ { "confidence": 1, "value": "user", "type": "value"
{
"entities": {
"entity": [
{
"confidence": 1,
"value": "user",
"type": "value"
},
{
"confidence": 1,
"value": "insurance form",
"type": "value"
}
],
"ui_page_step": [
{
"confidence": 1,
"value": "step 1",
"type": "value"
}
],
"userrole_ano": [
{
"confidence": 0.96535832252792,
"value": "anonymous user"
}
]
}
}
我需要将其转换为:
{
"entities": {
"entity": [
{
"name": "entity",
"confidence": 1,
"value": "user",
"type": "value"
},
{
"name": "entity",
"confidence": 1,
"value": "insurance form",
"type": "value"
}
],
"ui_page_step": [
{
"name": "ui_page_step",
"confidence": 1,
"value": "step 1",
"type": "value"
}
],
"userrole_ano": [
{
"name": "userrole_ano",
"confidence": 0.96535832252792,
"value": "anonymous user"
}
]
}
}
如何在Java中将原始响应转换为所需的响应?以下是几种可能的解决方案之一: 它使用库将Json解析为java映射,与JSONObject相比,java映射更易于导航和修改 putCollectionNamesInsideEntries方法假定一个根实体条目具有多个集合作为值。它将迭代所有这些项,并使用集合的名称添加名称项 映射被序列化回Json并发送到System.out
展示您迄今为止所做的一些尝试为什么要这样编辑JSON?有什么具体原因吗?您使用哪个库来反序列化JSON?第三方应用程序需要它作为响应。我还没有选择代码库,因为我不知道从哪里开始。使用JSONParser。解析它,并通过实体处的迭代器添加您的名称。你为什么到处打电话?ObjectMapper有非常酷的写入方法,可以直接在JsonNode->ArrayNode中写入任何我们喜欢的内容。@MS90,如果您能展示使用JsonMode和ArrayNode是多么容易,我将非常高兴。我发现使用这个api既困难又不直观
import java.io.*;
import java.nio.file.*;
import java.util.*;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTest
{
public static void main(String[] args) {
try (InputStream is = Files.newInputStream(Paths.get("C:/temp/test.json"))) {
ObjectMapper mapper = new ObjectMapper();
// deserialize json into map
Map<String, Object> map = (Map<String, Object>)mapper.readValue(is, Map.class);
putCollectionNamesInsideEntries(map);
// serialize map into json
mapper.writeValue(System.out, map);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void putCollectionNamesInsideEntries(Map<String, Object> map) {
// get root "entities" entry
Map<String, Object> entitiesMap = (Map<String, Object>)map.get("entities");
for (Map.Entry<String, Object> entitiesEntry : entitiesMap.entrySet()) {
// iterate over collection entries
if (entitiesEntry.getValue() instanceof Collection) {
Collection coll = (Collection)entitiesEntry.getValue();
// iterate over entries in collection
for (Object collEntry : coll) {
if (collEntry instanceof Map) {
// add "name" with ame of collection (key entry under "entries")
((Map<String, Object>)collEntry).put("name", entitiesEntry.getKey());
}
}
}
}
}
}