Get a specific value when parsing JSON with Jackson

I have the following JSON:

[  
   {  
      "A":"Lorem Ipsum ",
      "B":"Lorem Ipsum ",
      "C":"Lorem Ipsum ",
      "D":"Lorem Ipsum ",
      "E":"Lorem Ipsum ",
      "F":"Lorem Ipsum ",
      "G":301,
      "H":[  
         {  
            "Lorem Ipsum ":4,
            "Lorem Ipsum ":20,
            "Lorem Ipsum":0
         },
         {  
            "Lorem Ipsum ":5,
            "Lorem Ipsum ":19.2,
            "Lorem Ipsum ":0.8
         },
         {  
            "Lorem Ipsum ":1,
            "Lorem Ipsum ":8,
            "Lorem Ipsum ":4
         },
         {  
            "Lorem Ipsum ":3,
            "Lorem Ipsum ":14.2,
            "Lorem Ipsum ":5.8
         },
         {  
            "Lorem Ipsum ":2,
            "Lorem Ipsum ":20,
            "Lorem Ipsum ":0
         }
      ],
      "I":[  

      ],
      "J":[  

      ],
      "20-01-2014":20,
      "27-01-2014":19.2,
      "30-12-2013":8,
      "13-01-2014":14.2,
      "06-01-2014":20,
      "K":"81.40"
   },
   {  
      "reportKey":"something"
   }
]

I would like to get the value reportKeyand then delete it from the file. But first, I need to access it, and my code does not seem to work:

final ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readValue(rawContentParameters, JsonNode.class);

logger.info("ExportController : generatesExportExcel : parameters: {}", jsonNode.get("reportKey").textValue());

but i get java.lang.NullPointerException. Why?

DECISION:

final ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readValue(rawContentParameters, JsonNode.class);

logger.info("ExportController : generatesExportExcel : parameters: {}", rootNode.get(rootNode.size() - 1).get("reportKey").textValue());
+4
source share
3 answers

You gain access to the root JsonNodeas if it were an object, but it was wrapped in an array. You need to extract the second object from the array before you can access reportKey:

JsonNode array = objectMapper.readValue(rawContentParameters, JsonNode.class);
JsonNode object = array.get(1);
String reportKey = object.get("reportKey").textValue();
logger.info("ExportController : generatesExportExcel : parameters: {}", reportKey);
+4
source

First take the second item in the list.

jsonNode.get(1).get("reportKey")
+2
source

You can use the JSONObjectand JSONArrayof the org.json :

//instantiate your json array (e.g. from a string, or a file)
//String s = "[...]";
String s = FileUtils.readFileToString(new File(yourFile));
JSONArray json = new JSONArray(s);

//get the reportKey value:
json.get(1).get("reportKey");

//removing it:
//removing all the node: {"reportKey":"something"}
json.remove(1);
//removing only "reportKey":"something" and keeping {}:
json.get(1).remove("reportKey");
+1
source

All Articles