gpt4 book ai didi

Java : How to map the json string returned by Oauth2 service to model class object

转载 作者:行者123 更新时间:2023-11-30 07:14:56 24 4
gpt4 key购买 nike

我有一个 oauth2 服务器,当带有 granttype、用户凭据和客户端凭据的请求到来时,它将返回一个包含访问 token 、刷新 token 及其有效性的 json 字符串。下面是我得到的响应字符串。

{"value":"yu592e04-o9d5-8724-92a8-c5034df13cae","expiration":"Jul 25, 2016 4:14:31 PM","tokenType":"bearer","refreshToken":{"expiration":"Sep 24, 2016 3:14:31 PM","value":"bb6b7d65-a938-h75b-9cc5-d78b38e7adf9"},"scope":[],"additionalInformation":{}}

现在我需要将 json 字符串中的所有这些字段映射到一个类。我该怎么做。我需要将字段映射到下面的类。

public class UserToken{
String accessToken;
Date accessTokenValidity;
String accessTokenType;
String refreshToken;
Date refreshTokenValidity;
String scope;
}

最佳答案

您可以使用 Jackson 库来做到这一点。

试试这个。 refreshToken 标记成为 java 中的一个类。

public class Convertor {

public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String json = "{\"value\":\"yu592e04-o9d5-8724-92a8-c5034df13cae\",\"expiration\":\"Jul 25, 2016 4:14:31 PM\",\"tokenType\":\"bearer\",\"refreshToken\":{\"expiration\":\"Sep 24, 2016 3:14:31 PM\",\"value\":\"bb6b7d65-a938-h75b-9cc5-d78b38e7adf9\"}}";
Convertor converter = new Convertor();
UserToken token = converter.fromJson(json);
System.out.println(token);

}

public UserToken fromJson(String json) throws JsonParseException, JsonMappingException, IOException {
UserToken token = (UserToken) new ObjectMapper().readValue(json, UserToken.class);

return token;
}

}

class UserToken {

String value;
String expiration;
String tokenType;
RefreshToken refreshToken;

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}

public String getExpiration() {
return expiration;
}

public void setExpiration(String expiration) {
this.expiration = expiration;
}

public String getTokenType() {
return tokenType;
}

public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}

public RefreshToken getRefreshToken() {
return refreshToken;
}

@JsonProperty("refreshToken")
public void setRefreshToken(RefreshToken refreshToken) {
this.refreshToken = refreshToken;
}



@Override
public String toString() {

return "value " + value + "expiration " + expiration + "refreshToken.Expiration " + refreshToken.getExpiration()
+ " refreshToken.getValue: " + refreshToken.getValue();
}
}

class RefreshToken {
String expiration;
String value;

public String getExpiration() {
return expiration;
}

public void setExpiration(String expiration) {
this.expiration = expiration;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}

}

关于Java : How to map the json string returned by Oauth2 service to model class object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38564710/

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