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

Jackson ObjectMapper readValue() unrecognized field when parsing to Object

我正在 Java/Spring 中创建简单的休息客户端。我的请求已被远程服务正确处理,我得到了响应 String something:

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

下面的代码是我要绑定来自 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;
}
}

我总是得到 "unrecognized field 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"

您的设置器与 JSON 键不匹配。

要正确阅读,您应该将设置器更改为:

setAccess_token()
setToken_type()
...

但老实说,这太丑了。

尝试遵循 Java bean 名称约定并使用 @JsonProperty 自定义 JSON 键:

public class Token {
        @JsonProperty("access_token")
        String accessToken;
         ....

}

您尝试使用 "@JsonProperty(accessToken)"。但是你的 json 包含 access_token。怎么运行的? 试试这个 class:

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