![](/img/trans.png)
[英]How to add name to List in jSON Array, posting response using springboot
[英]How to add the name before the array in the array object itself in a JSON response?
我正在使用外部Web服务并收到JSON响应。 在此响应中,有一个对象“实体”,其中包含多个数组,每个数组之前都有一个名称。
我想在数组对象本身中的数组之前添加名称。
例如,这是原始响应:
{
"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中将原始响应转换为所需的响应?
这是(几种可能的一种)解决方案:
它使用Jackson库将Json解析为一个Java Map
,相对于JSONObject,该Java Map
(相对)更易于浏览和修改。
方法putCollectionNamesInsideEntries()
假定一个根"entities"
条目具有多个集合作为值。 它遍历所有这些对象,并添加"name"
条目和集合名称。
映射序列化回Json(并发送到System.out
)
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()); } } } } } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.