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

We Are Going To Discuss About java.lang.NullPointerException: Cannot invoke method get() on null object. So lets Start this Java Article.

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

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

    object.get() will give an NullPointerException if the object is null, so you need to check if the object is null or not before you call any method on it. so, an alternative could to check if astros != null and then call .get() within the if-block.

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

    object.get() will give an NullPointerException if the object is null, so you need to check if the object is null or not before you call any method on it. so, an alternative could to check if astros != null and then call .get() within the if-block.

Solution 1

object.get() will give an NullPointerException if the object is null, so you need to check if the object is null or not before you call any method on it. so, an alternative could to check if astros != null and then call .get() within the if-block.

Original Author Vineeth Sai Of This Content

Solution 2

Handle the null issue inside your code as follows (Use null safe operator and groovy truth concept.)

@Grab('io.github.http-builder-ng:http-builder-ng-core:1.0.3')

import static groovyx.net.http.HttpBuilder.configure
def astros = configure {
    request.uri = 'http://api.open-notify.org/astros.json'
}?.get() // added null safe operator here (will handle null pointer exception)

println "There are ${astros?.number} astronauts in space right now."
//iterate if astros value exists.
if(astros){
  astros.people.each { p->
    println " - ${p.name} (${p.craft})"
  }
}

// As you are having json, you need to parse that as follows.

  def slurper = new groovy.json.JsonSlurper()
  def result = slurper.parseText(astros)
  println result
  println result?.number

Original Author Nitin Dhomse Of This Content

Solution 3

I take it that you created a shared library and is trying to use this in a pipeline?

I have the same problem at the moment, I think it might be a limitation of the Groovy interpreter on Jenkins, similar to how the each loop didn’t work until some time ago.

I’ve resorted to using this version of http-builder to circumvent that for now. I’ll update this if I find a proper solution (please also post an answer if you find anything).

Original Author Marcos Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment