简体   繁体   中英

How to add the name before the array in the array object itself in a JSON response?

I am consuming an external web service and receiving a JSON response. In this response, there is an object "entities" containing multiple arrays in it, with a name before each array.

I want to add the name before the array in the array object itself.

For example this is the original response:

{

    "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"
            }
        ]
    }
}

I need to convert it to:

{
  "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"
      }
    ]
  }
}

How can I convert the original response to the desired one in Java?

Here is a (one of several possible) solutions:

  1. It uses Jackson library to parse the Json into a java Map that is (relatively) easier to navigate and modify than JSONObject.

  2. the method putCollectionNamesInsideEntries() assumes one root "entities" entry that has several collections as values. it iterates over all of them, adding "name" entry with name of collection.

  3. the map is serialized back to Json (and sent to 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()); } } } } } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM