Why ‘String Cannot Be Converted to JSONObject’ Occurs and How to Fix It
In the journey of developing applications, especially those that process API responses or work with JSON data, encountering the error String cannot be converted to JSONObject can be frustrating. This article dives deep into the reasons why this e...

I am Tuanh.net. As of 2024, I have accumulated 8 years of experience in backend programming. I am delighted to connect and share my knowledge with everyone.
1. Understanding the Error: What Does It Mean?
1.1 Basic Definition of JSONObject
{
"key": "value",
"anotherKey": 42
}
1.2 Common Causes
- The string is not in valid JSON format (e.g., a plain string instead of JSON).
- The string contains additional characters, such as a newline or whitespace, that prevent parsing.
- The API response is unexpected, such as returning XML or plain text instead of JSON.
- Improper encoding or decoding during transmission.
2. Resolving the Issue with Practical Examples
2.1 Validate the Input String
import org.json.JSONObject;
public class JsonValidator {
public static boolean isValidJson(String json) {
try {
new JSONObject(json);
return true;
} catch (Exception e) {
return false;
}
}
public static void main(String[] args) {
String input = "{ "name": "Tuan Anh", "age": 30 }";
if (isValidJson(input)) {
System.out.println("Valid JSON: " + input);
} else {
System.out.println("Invalid JSON");
}
}
}
- This code checks whether a given string is valid JSON.
- If the string is invalid, you can handle it gracefully instead of letting the application crash.
2.2 Handle Unexpected API Responses
import org.json.JSONObject;
public class ApiResponseHandler {
public static void processResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
System.out.println("Parsed JSON: " + jsonObject);
} catch (Exception e) {
System.out.println("Invalid response format: " + response);
}
}
public static void main(String[] args) {
String apiResponse = "<html>Error 404: Not Found</html>"; // Simulated API response
processResponse(apiResponse);
}
}
- This code demonstrates how to safeguard against non-JSON responses from APIs.
- By wrapping the parsing operation in a try-catch block, it catches exceptions and logs invalid data.
2.3 Strip Unnecessary Characters
import org.json.JSONObject;
public class JsonCleaner {
public static String cleanJsonString(String input) {
return input.trim(); // Removes leading and trailing whitespace
}
public static void main(String[] args) {
String rawInput = " {"key":"value"} ";
String cleanedInput = cleanJsonString(rawInput);
try {
JSONObject jsonObject = new JSONObject(cleanedInput);
System.out.println("Cleaned and Parsed JSON: " + jsonObject);
} catch (Exception e) {
System.out.println("Error parsing JSON");
}
}
}
- This solution trims unnecessary spaces or characters from the string before parsing.
- It’s particularly useful when dealing with inconsistent input formats.
3. Preventive Measures and Best Practices
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class GsonExample {
public static void main(String[] args) {
String jsonString = "{ "name": "Tuan Anh", "role": "Developer" }";
try {
JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
System.out.println("Parsed with Gson: " + jsonObject);
} catch (Exception e) {
System.out.println("Failed to parse JSON");
}
}
}
4. Common Pitfalls and Troubleshooting
5. Conclusion
Read more at : Why ‘String Cannot Be Converted to JSONObject’ Occurs and How to Fix It





