【问题标题】:How to access a value from JSON object returned by Google Api(userinfo) in Java如何从 Java 中的 Google Api(userinfo) 返回的 JSON 对象中访问值
【发布时间】:2016-02-26 18:31:39
【问题描述】:

我只想从 Google API 返回的 JSON 中访问电子邮件地址和姓名。下面是我的代码的 sn-p。 jsonIdentity 返回整个 Json

字符串 USER_INFO_URL = "https://www.googleapis.com/oauth2/v1/userinfo";

public String getUserInfoJson(final String authCode) throws IOException {
    final GoogleTokenResponse response = flow.newTokenRequest(authCode).setRedirectUri(REDIRECT_URI).execute();
    final Credential credential = flow.createAndStoreCredential(response, null);
    final HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential);
    final GenericUrl url = new GenericUrl(USER_INFO_URL);
    final HttpRequest request = requestFactory.buildGetRequest(url);
    request.getHeaders().setContentType("application/json");
    final String jsonIdentity = request.execute().parseAsString();
    return jsonIdentity;

}

【问题讨论】:

标签: java json jsp jakarta-ee oauth


【解决方案1】:

添加maven依赖:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160212</version>
</dependency>

并使用:

JSONObject jsonObject = new JSONObject(jsonIdentity);
String email = jsonObject.getString("email");

【讨论】:

  • 工作就像一个魅力!谢谢!
【解决方案2】:

由于您使用的是 Google API,您可能需要考虑使用 Google-GSON 库来解析 JSON。

Google-GSON 的基本用法如下:

Gson gson = new Gson(); // This object is reusable so I'd cache it rather than keep recreating it.
DataObject d = gson.fromJson(jsonString, DataObject.class);

View the User Guide for more information.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多