java.lang.NullPointerException:无法在null对象

时间:2018-01-30 12:31:30

标签: java jenkins groovy jenkins-pipeline

我有下一个Groovy代码,我尝试在Jenkins管道中运行:

@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()

println "There are ${astros.number} astronauts in space right now."

astros.people.each { p->
    println " - ${p.name} (${p.craft})"
}

但每次我收到java.lang.NullPointerException: Cannot invoke method get() on null object错误。

当我从桌面运行它时,一切都按预期工作:

There are 6 astronauts in space right now.

詹金斯:

There are null astronauts in space right now.

调试输出:

<groovyx.net.http.UriBuilder$Basic@4bc2413c scheme=http port=-1 host=api.open-notify.org path=/astros.json query=[:] fragment=null userInfo=null parent=groovyx.net.http.UriBuilder$ThreadSafe@69c6847a useRawValues=null>

我该怎么做才能让它发挥作用?

3 个答案:

答案 0 :(得分:0)

如果对象为null,

object.get()将给出NullPointerException,因此在调用任何方法之前,需要检查对象是否为null。因此,另一种方法是检查是否astros != null,然后在if-block中调用.get()

答案 1 :(得分:0)

在代码中处理null问题,如下所示(使用null safe operator和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})"
  }
}

//当你拥有json时,你需要解析如下。

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

答案 2 :(得分:0)

我认为你创建了一个共享库并试图在管道中使用它?

我目前遇到同样的问题,我认为这可能是Jenkins上Groovy解释器的限制,类似于每个循环没有工作until some time ago

我现在使用这个版本的http-builder来规避这个问题。如果我找到合适的解决方案,我会更新此信息(如果您发现任何问题,也请发布答案)。