📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!

  • google app store apple app store
  • ✖

      Question

      You are trying to parse a JSON string in Java using a

      library like org.json. import org.json.JSONObject; import org.json.JSONException; public class JsonParser {     public static void main(String[] args) {         String jsonString = "{'name': 'Alice', 'age': 30}"; // Potential bug here         try {             JSONObject jsonObject = new JSONObject(jsonString);             System.out.println("Name: " + jsonObject.getString("name"));         } catch (JSONException e) {             System.err.println("JSON Parsing Error: " + e.getMessage());         }     } } What is the most likely error this Java code will encounter when trying to parse jsonString?
      A NullPointerException because jsonString is not valid. Correct Answer Incorrect Answer
      B JSONException because JSON requires double quotes for string literals and keys. Correct Answer Incorrect Answer
      C ClassCastException because age is an integer, not a string. Correct Answer Incorrect Answer
      D FileNotFoundException because the JSON is not from a file. Correct Answer Incorrect Answer
      E No error, it will parse correctly. Correct Answer Incorrect Answer

      Solution

      • Dry Run: o The JSONObject constructor will attempt to parse the jsonString. o When it encounters the single quotes, it will recognize that the string does not conform to the standard JSON specification. o The org.json library (and most other JSON parsers) will throw a JSONException because of the invalid syntax. • Why Correct Answer (B): JSONException because JSON requires double quotes for string literals and keys. o This is the fundamental reason for the parsing failure. The org.json library is strict about JSON syntax.

      Practice Next
      ask-question