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

标签 java json rest jackson objectmapper

我正在使用 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/

相关文章:

java - 在 Grails Spring Data 应用程序中混合 java 和 groovy 代码时出错

ruby-on-rails - Rails 4.0 的自定义错误处理

java - android json数据到spring mvc4

javascript - Express + node.js API 过滤

java - 如何使用 JFileChooser 将最后一个路径设置为下一个默认路径

java - 添加额外的 getter 和 setter 后出现 JPA 异常

javascript - KnockoutJS - 无法从纯 JSON 数组映射模型

javascript - 是否可以使用仅限客户端的单页应用程序实现 SEO?

通过 REST Json 的 JavaFX2 客户端-服务器

java - 如何升级用户手机中的sqlite数据库