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());
Reading JSON from a File Thankfully, Jackson makes this task as easy as the last one, we just provide the File to the readValue() method: final ObjectMapper objectMapper = new ObjectMapper(); List<Language> langList = objectMapper. readValue( new File("langs. json"), new TypeReference<List<Language>>(){}); langList.
Read Object From JSON via URL ObjectMapper objectMapper = new ObjectMapper(); URL url = new URL("file:data/car. json"); Car car = objectMapper. readValue(url, Car. class);
A JsonNode is Jackson's tree model for JSON and it can read JSON into a JsonNode instance and write a JsonNode out to JSON. To read JSON into a JsonNode with Jackson by creating ObjectMapper instance and call the readValue() method. We can access a field, array or nested object using the get() method of JsonNode class.
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);
First take second element on the list.
jsonNode.get(1).get("reportKey")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With