gpt4 book ai didi

java - Jackson ObjectMapper readValue() 解析为对象时无法识别字段

转载 作者:行者123 更新时间:2023-11-30 06:03:35 25 4
gpt4 key购买 nike

我正在使用 Java/Spring 创建简单的休息客户端。我的请求已被远程服务正确使用,并且我收到了响应 String 某些内容:

{"access_token":"d1c9ae1b-bf21-4b87-89be-262f6","token_type":"bearer","expires_in":43199,"grant_type":"client_credentials"}
<小时/>

下面的代码是我想要绑定(bind) Json 响应中的值的对象

package Zadanie2.Zadanie2;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Token {
String access_token;
String token_type;
int expiresIn;
String grantType;
//////////////////////////////////////////////////////
public Token() {
/////////////////////////////////
}
/////////////////////////////////////////////////////

public void setAccessToken(String access_token) {
this.access_token=access_token;
}
public String getAccessToken() {
return access_token;
}
////////////////////////////////////////////////
public void setTokenType(String token_type) {
this.token_type=token_type;
}
public String getTokenType() {
return token_type;
}
//////////////////////////////////////////////////////
public void setExpiresIn(int expiresIn) {
this.expiresIn=expiresIn;
}
public int getExpiresIn() {
return expiresIn;
}
//////////////////////////////////////////////////////////
public void setGrantType(String grantType) {
this.grantType=grantType;
}
public String getGrantType() {
return grantType;
}
}

我一直收到“无法识别的字段access_token”,但是当我添加objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 那么access_token将为null

        jsonAnswer=template.postForObject(baseUriAuthorize, requestEntity,  String.class);  
System.out.println(jsonAnswer);
Token token=objectMapper.readValue(jsonAnswer, Token.class);
System.out.println(token.getAccessToken());

我尝试使用@JsonProperty注释。我尝试通过例如 "@JsonProperty(accessToken)" 更改字段,因为我认为变量名称中的“_”符号存在问题。我添加了 getter 和 setter。也许我使用的版本有问题,但我不这么认为,因为我使用的是 "com.fasterxml.jackson.core"

最佳答案

您尝试使用“@JsonProperty(accessToken)”。但是您的 json 包含 access_token。怎么运行的?尝试使用此类:

public class Token {
@JsonProperty("access_token")
String accessToken;
@JsonProperty("token_type")
String tokenType;
int expiresIn;
String grantType;
//getter setter
}

关于java - Jackson ObjectMapper readValue() 解析为对象时无法识别字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51807693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com