Reputation: 2038
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'd like to get the reportKey
value and then remove it from the file. But first I need to access it and my code doesn't 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'm getting a java.lang.NullPointerException
. Why?
SOLUTION:
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());
Upvotes: 7
Views: 28449
Reputation: 24393
You are accessing the root JsonNode
as if it were an object, but it's 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);
Upvotes: 10
Reputation: 2693
You can use JSONObject
and JSONArray
from org.json library :
//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");
Upvotes: 1
Reputation: 3966
First take second element on the list.
jsonNode.get(1).get("reportKey")
Upvotes: 2