簡體   English   中英

使用Java中的Gson解析來自HTTP請求的JSON響應

[英]Parsing JSON response from an HTTP request with Gson in Java

我正在嘗試從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"
    }
}

我正在嘗試獲取兩個值“status: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。

您需要先使用Gson獲取data對象,然后才能訪問其字段:

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

您使用了兩個庫進行JSON解析,在此上下文中不需要。 假設你想使用Gson 刪除JSONParser jsonParser = new JSONParser();

現在,在您的JSON數據activation_id可以達到Root -> data -> activation_id Root表示存儲到jsonObject整個JSON對象。 data鍵本身代表一個對象。 因此,我們可以通過獲取data鍵值作為對象來達到activation_id ,然后將activation_id作為int / string。

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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM