0

I recently stumbled on an issue with parsing mapping values which are handed over via a List.

I receive a Json and within the JSON there is an extra field attributes. Which looks like this

"attributes": [
  {
    "id": "id",
    "value": "12345677890124566"
  },
  {
    "id": "Criticality",
    "value": "medium"
  },
  {
    "id": "type",
    "value": "business"
  },
  {
    "id": "active",
    "value": "true"
  }
],

I fetch it via parsing it into a List via (List<Map<String, String>>) request.get("attributes") attributes. I parse through the list via : for (Map<String, String> attribute : attributes).

I am not able to get the value of any attribute. I tried stuff like get("active"), containsKey and much more the only result I get is null.

I tried parsing the value from the mapping for an attribute but received only null instead of the value.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

2 Answers2

0

You attributes data is not a map in the Java sense. It is an array of objects each with an id and a value.

This will work:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;

public class AttributeParser {

    public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper() ;

        String requestJSON = "{ \"attributes\": [\r\n"
                + "    {\r\n"
                + "      \"id\": \"id\",\r\n"
                + "      \"value\": \"12345677890124566\"\r\n"
                + "    },\r\n"
                + "    {\r\n"
                + "      \"id\": \"Criticality\",\r\n"
                + "      \"value\": \"medium\"\r\n"
                + "    },\r\n"
                + "    {\r\n"
                + "      \"id\": \"type\",\r\n"
                + "      \"value\": \"business\"\r\n"
                + "    },\r\n"
                + "    {\r\n"
                + "      \"id\": \"active\",\r\n"
                + "      \"value\": \"true\"\r\n"
                + "    }\r\n"
                + "  ]}";
        
        JsonNode request = objectMapper.readTree(requestJSON);
        
        ArrayNode attributesNode = (ArrayNode) request.get("attributes");
        
        attributesNode.forEach(jsonNode -> {
            System.out.println("id: " + jsonNode.get("id").asText() + ", value: " + jsonNode.get("value").asText());
            });
        
        
    }

}
John Williams
  • 4,252
  • 2
  • 9
  • 18
-1

you try to access to map data with get("active") but you should use get("value")

i hope this example can help :

   for(Map<String, String> attribute: attributes){
     String value = attribute.get("value");
     system.out.print(value); }
Wbh52
  • 9
  • 6