Android中使用HttpURLConnection解析JSON获取指定字段值
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-catchblock: Network responses might not be valid JSON, or the "USD_PKR" key could be missing, so this prevents your app from crashing. - The
org.jsonpackage 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

