You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中使用HttpURLConnection解析JSON获取指定字段值

Extracting USD_PKR Value from Your JSON Response

Hey there! Since your response is a simple JSON object, you can use Android's built-in org.json library to parse it without any extra dependencies. Here's how to modify your code to get that 115.599998 value:

Step 1: Parse the JSON in doInBackground

Assuming you've already fetched the response body into a String variable (let's call it responseString), add this parsing logic inside your doInBackground method:

@Override
protected String doInBackground(String... params) {
    String responseString = "";
    
    // Your existing code to fetch the response via HttpURLConnection goes here
    // ... (make sure you populate responseString with the server's JSON output)
    
    // Parse the JSON to extract the rate
    try {
        JSONObject jsonResponse = new JSONObject(responseString);
        double usdToPkrRate = jsonResponse.getDouble("USD_PKR");
        
        // Since your AsyncTask returns a String, convert the double to a String to return it
        return String.valueOf(usdToPkrRate);
    } catch (JSONException e) {
        // Handle parsing errors (e.g., invalid JSON or missing key)
        e.printStackTrace();
        return "Failed to parse rate";
    }
}

Step 2: Use the Value in onPostExecute

Once doInBackground returns the rate as a String, you can use it in onPostExecute to update your UI or do further processing:

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    // Check if we got a valid rate
    if (!result.equals("Failed to parse rate")) {
        double rate = Double.parseDouble(result);
        // Example: Display the rate to the user
        // Toast.makeText(getApplicationContext(), "USD to PKR: " + rate, Toast.LENGTH_SHORT).show();
    } else {
        // Show error message
        // Toast.makeText(getApplicationContext(), "Error fetching rate", Toast.LENGTH_SHORT).show();
    }
}

Optional: Simplify by Changing AsyncTask's Return Type

If you want to work with the numeric value directly instead of converting between String and Double, you can adjust your AsyncTask's generic parameters to return a Double instead of String:

private class MakeNetworkCall extends AsyncTask<String, Void, Double> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // DisplayMessage("Please Wait ...");
    }

    @Override
    protected Double doInBackground(String... params) {
        String responseString = "";
        // Your network fetch code here
        // ...
        
        try {
            JSONObject jsonResponse = new JSONObject(responseString);
            return jsonResponse.getDouble("USD_PKR");
        } catch (JSONException e) {
            e.printStackTrace();
            return null; // Return null on error
        }
    }

    @Override
    protected void onPostExecute(Double rate) {
        super.onPostExecute(rate);
        if (rate != null) {
            // Use the double value directly
            // DisplayMessage("USD to PKR rate: " + rate);
        } else {
            // Handle error scenario
        }
    }
}

Key Notes:

  • Always wrap JSON parsing in a try-catch block: Network responses might not be valid JSON, or the "USD_PKR" key could be missing, so this prevents your app from crashing.
  • The org.json package is included with Android, so you don't need to add any external libraries like Gson or Moshi unless you're dealing with more complex JSON structures.

内容的提问来源于stack exchange,提问作者Usman Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:00:55