无法通过WebClient从API调用中接收数据
因此,我试图绕过网络客户,但是我一直在获得NullPoInterException,尽管我的测试工作正常,并且说该对象不是空的。我还看到我的控制台连接到API。但是当我问值时,我会毫无意义。
这是我使用的两个对象:
import com.fasterxml.jackson.annotation.JsonProperty;
public class Data {
@JsonProperty("message")
private String message;
@JsonProperty("status")
private String status;
public String getMessage() {
return message;
}
public String getStatus() {
return status;
}
}
public class Foto {
private Data data;
public Data getData() {
return data;
}
}
然后在这里我有我的API调用,我已经放入PSVM以获取控制台结果:
try {
var test = client.get()
.uri("https://dog.ceo/api/breeds/image/random")
.retrieve()
.bodyToMono(Foto.class)
.block();
System.out.println(test.getData().getMessage());
} catch (WebClientResponseException.NotFound ex) {
ex.getMessage();
}
}
但是作为System.Out.println的控制台输出。 “ main” java.lang.nullpointerexception:无法调用” be.hi10.apeSt.domain.data.getMessage()”,因为be.hi10.apiestest.foto.getdata()的返回值 在be.hi10.apeest.apiest.apiestapplication.main(apiesteStapplication.java:31)
我在这里做错了什么?我应该收到代表图像的URL的字符串。
So I'm trying to get my head around the webclient, but I keep getting a nullpointerexception, though my test work fine and say that object is not null. I also see my console making connection to the api. But when I ask the value, I get null.
Here are the two objects I use for it:
import com.fasterxml.jackson.annotation.JsonProperty;
public class Data {
@JsonProperty("message")
private String message;
@JsonProperty("status")
private String status;
public String getMessage() {
return message;
}
public String getStatus() {
return status;
}
}
public class Foto {
private Data data;
public Data getData() {
return data;
}
}
and then here I have my api call, I've put in my psvm to get console results:
try {
var test = client.get()
.uri("https://dog.ceo/api/breeds/image/random")
.retrieve()
.bodyToMono(Foto.class)
.block();
System.out.println(test.getData().getMessage());
} catch (WebClientResponseException.NotFound ex) {
ex.getMessage();
}
}
But as a console output for the system.out.println I keep receiving: Exception in thread "main" java.lang.NullPointerException: Cannot invoke "be.hi10.apiesTest.domain.Data.getMessage()" because the return value of "be.hi10.apiesTest.domain.Foto.getData()" is null
at be.hi10.apiesTest.ApiesTestApplication.main(ApiesTestApplication.java:31)
What am I doing wrong here? I should be receiving a String representing a url to an image.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请注意,您的API返回这样的响应:
因为您试图将您的响应转换为foto类,它看起来像这样:
为此,您的JSON应该必须看起来像这样:
但这不是,这就是为什么您的避免化失败而您的原因。获取
NullPoInterException
。为了使这项工作,将响应类型更改为
data
:Notice that your api returns response like this :
Since you are trying to convert your response to Foto class which looks like this :
For that to work your JSON should have to look like this :
but it doesnt and thats why your deserilization fails and you are getting
NullPointerException
.To make this work, change response type to
Data
: