- jackson的maven依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
- @JsonProperty 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把accessToken属性序列化为access_token,@JsonProperty(value=“access_token”)
/**
* 用户授权token
*
*/
public class UserAccessToken {
//获取到的凭证
@JsonProperty("access_token")
private String accessToken;
//凭证有效时间,单位:秒
@JsonProperty("expires_in")
private String expiresIn;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(String expiresIn) {
this.expiresIn = expiresIn;
}
}
- 测试
public class Main {
public static void main(String[] args) throws JsonProcessingException {
String tokenStr = “{\"access_token\":\"ACCESS_TOKEN\",\"expires_in\":7200}”
UserAccessToken token = new UserAccessToken();
ObjectMapper objectMapper = new ObjectMapper();
// 将json字符串转换成相应对象
token = objectMapper.readValue(tokenStr, UserAccessToken.class);
}
}