Android Studio中从JSONObject提取‘ok’字符串的方法求助
解决Android中提取响应里的"ok"字符串问题
Hey there! Let's work through this together—glad you already got the server response working in your Android Studio 3 emulator, that's half the battle done!
First, let's clarify a key point: you need to know exactly what your server's response looks like before extracting the "ok" string. Let's break down the two most common scenarios and the code for each:
1. If the server returns plain text "ok"
If the response is just the raw string "ok" (not wrapped in a JSON object), you can directly convert the response body to a string and check it:
// Example with OkHttp (adjust if you're using HttpURLConnection) try { Response response = client.newCall(request).execute(); if (response.isSuccessful()) { String responseBody = response.body().string().trim(); // Trim whitespace just in case if ("ok".equals(responseBody)) { // You've got your "ok" string here! Log.d("TAG", "Extracted string: " + responseBody); } else { Log.d("TAG", "Response wasn't 'ok': " + responseBody); } } } catch (IOException e) { e.printStackTrace(); }
2. If the server returns a JSON object with an "ok" field
If the response is a JSON object like {"status": "ok"} (or any other key that holds the "ok" value), use Android's built-in org.json library to parse it:
try { Response response = client.newCall(request).execute(); if (response.isSuccessful()) { String responseBody = response.body().string(); JSONObject jsonResponse = new JSONObject(responseBody); // Replace "status" with the actual key from your JSON String targetString = jsonResponse.getString("status"); if ("ok".equals(targetString)) { Log.d("TAG", "Found 'ok'!"); } else { Log.d("TAG", "Got: " + targetString); } } } catch (IOException | JSONException e) { e.printStackTrace(); // Handle network or parsing errors here }
Quick Troubleshooting Tips
- Print the full response first: Add
Log.d("TAG", "Full response: " + responseBody);right after getting the response string. This will show you exactly what you're working with—no more guessing! - Watch for case sensitivity: JSON keys and string values are case-sensitive. Make sure you're checking for
"ok"(all lowercase) and not"Ok"or"OK". - Handle nulls: If the JSON field might be missing, use
jsonResponse.optString("status")instead ofgetString()—it returns an empty string if the key doesn't exist, avoiding aJSONException.
内容的提问来源于stack exchange,提问作者Vit
相关产品推荐
相关产品推荐

