首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >用Gson在Java中解析HTTP请求的JSON响应

用Gson在Java中解析HTTP请求的JSON响应
EN

Stack Overflow用户
提问于 2019-05-24 02:54:15
回答 2查看 2.5K关注 0票数 0

我正在尝试从URL读取以下json输出

代码语言:javascript
复制
{
    "error": false,
    "status": 200,
    "message": "License Key activated successfully.",
    "data": {
        "expire": 1582657054,
        "activation_id": 1519628117,
        "expire_date": "2020-02-25 18:57",
        "timezone": "UTC",
        "the_key": "Cqu62al903ICv40am9nM68Y7o9-32",
        "url": "http://domain/my-account/view-license-key/?key=test-32",
        "has_expired": false,
        "status": "active",
        "allow_offline": true,
        "offline_interval": "days",
        "offline_value": 1,
        "downloadable": {
            "name": "v1.1.5",
            "url": "https://domain/product-1.1.5.zip"
        },
        "ctoken": "dsfejk8989"
    }
}

我正在尝试获取"status: 200“和"activation_id”这两个值。

我尝试过在线查找和解析。似乎什么都不起作用。对于整个json阅读,我还是个新手。

代码语言:javascript
复制
try {
    JSONParser jsonParser = new JSONParser();

    String jsonS = "";
    URL url = new URL(link);
    URLConnection conn = url.openConnection();
    conn.connect();
    BufferedReader in = new BufferedReader(new InputStreamReader(
            conn.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        jsonS += inputLine;
    }

    Gson gson = new Gson();
    JsonObject jsonObject = gson.fromJson(jsonS, JsonObject.class);
    int id = jsonObject.get("status").getAsInt();

    cintout(id);
    cout(link);
    cout(inputLine);
    try {

        if (id == 200)
            return ValidationType.VALID;
        else
            return ValidationType.WRONG_RESPONSE;
    } catch (IllegalArgumentException exc) {

        if (id == 200)
            return ValidationType.VALID;
        else
            return ValidationType.WRONG_RESPONSE;
    }
} catch (IOException e) {
    e.printStackTrace();
    return ValidationType.VALID;
}

我已经设法检索到了状态值,但没有检索到激活id。

EN

回答 2

Stack Overflow用户

发布于 2019-05-24 03:02:33

您需要使用Gson获取data对象,然后才能访问它的字段:

代码语言:javascript
复制
int activation_id = jsonObject.get("data").getAsJsonObject().get("activation_id").getAsInt();
票数 0
EN

Stack Overflow用户

发布于 2019-05-24 03:26:10

您使用了两个库来进行JSON解析,这在本文中不是必需的。假设您想要使用Gson。删除JSONParser jsonParser = new JSONParser();

现在,在您的JSON数据中,可以通过Root -> data -> activation_id访问activation_id。根代表存储到jsonObject中的整个JSON对象。data密钥本身代表一个对象。因此,我们可以通过将data键值作为对象来获取activation_id,然后以整数/字符串的形式获取activation_id

代码语言:javascript
复制
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonS, JsonObject.class);
int id = jsonObject.get("status").getAsInt();
int activationId = jsonObject.get("data").getAsJsonObject().get("activation_id").getAsInt();

有关json对象的更多信息:https://www.shapediver.com/blog/json-objects-explained/

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56281361

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档