首页 > 解决方案 > 在 Java 中使用 Gson 解析来自 HTTP 请求的 JSON 响应

问题描述

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

{
    "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"
    }
}

我正在尝试获取两个值“状态:200”和“activation_id”。

我试过在线查找和解析。似乎没有任何效果。我对整个 json 阅读有点陌生。

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。

标签: javajsonhttpparsinggson

解决方案


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

int activation_id = jsonObject.get("data").getAsJsonObject().get("activation_id").getAsInt();

推荐阅读