java.lang.NullPointerException: Cannot invoke method getAt() on null object

API Response is throwing the following error while getting the Response Body. Any thoughts on this, please ?

Here is the response body - the following email records can be 1000s.

[
{
“emails”:[
{
“_id”:“1234”,
email":"user1@some.com”,
“mid”:110,
“lastName”:“User1”,
“firstName”:“Bulk”
},
{
“_id”:“2345”,
email":"user2@some.com”,
“marid”:111,
“lastName”:“User2”,
“firstName”:“Bulk”
},
{
“_id”:“3456”,
email":"user2@some.com”,
“marid”:112,
“lastName”:“User3”,
“firstName”:“Bulk”
}
]

Error is as below :
java.lang.NullPointerException: Cannot invoke method getAt() on null object

When I tried it using Json Path Finder. it shows :
x[0].emails[0]._id
x[0].emails[0].email
x[0].emails[0].maid
x[0].emails[0].lastName

etc…

what is your X? and which line of code causing the error?

@Brian_Ducson

My code is failing here -
String responseBody = response.getResponseText()
JsonSlurper slurper = new JsonSlurper()
Map parsedJson = slurper.parseText(responseBody)

String emailId = parsedJson.emails[0]._id
println (emailId)

your response is an array of objects so you have to reach them by:
String emailId = parsedJson[0].emails[X]

1 Like

A JSON object can be either type of java.util.Map, java.util.List.

This is a JSON as a List of Strings

["hello", "world"]

This is a JSON as a Map of <String, String>

{ "greeting": "hello", "to":"world"}

The data type of the parsedJson variable created by JsonSlurper depends on the actual text content.

If you do not want restrict the type of the parsedJson variable, you can use Groovy’s keyword def like the following code

String responseBody = response.getResponseText()
JsonSlurper slurper = new JsonSlurper()
def parsedJson = slurper.parseText(responseBody)
String emailId = parsedJson.emails[0]._id
println (emailId)

The def keyword means java.lang.Object actually. Both of List and Map are Object. So syntactically valid.

2 Likes

@kazurayam, @Ibus
Both the resolutions worked.

@kazurayam - Thank you for the nice explanation about the map and list.

Appreciate your help.