Org.Json - CSV Examples
Org.Json - Cookie Examples
Org.Json - HTTP Header Examples
Org.Json - JSON Examples
Org.Json - Property Examples
Org.Json - XML Examples
Org.Json - Exception Handling
Org.Json - Useful Resources
Org.Json - JSONException Handling
Utility classes of org.json throws JSONException in case of invalid JSON. Following example shows how to handle JSONException.
Example - Handling JSONException
JsonDemo.java
package com.tutorialspoint;
import org.json.JSONException;
import org.json.XML;
public class JsonDemo {
public static void main(String[] args) {
try {
//XML tag name should not have space.
String xmlText = "<Other Details>null</Other Details>";
System.out.println(xmlText);
//Convert an XML to JSONObject
System.out.println(XML.toJSONObject(xmlText));
}
catch(JSONException e){
System.out.println(e.getMessage());
}
}
}
Output
<Other Details>null</Other Details> Misshaped close tag at 34 [character 35 line 1]
Example - Throwing JSONException
JSONException is a Runtime Exception and is not required to be declared as throws statement. But we can throw it to make code clearer and cleaner.
JsonDemo.java
package com.tutorialspoint;
import org.json.JSONException;
import org.json.XML;
public class JsonDemo {
public static void main(String[] args) throws JSONException {
//XML tag name should not have space.
String xmlText = "<Other Details>null</Other Details>";
System.out.println(xmlText);
//Convert an XML to JSONObject
System.out.println(XML.toJSONObject(xmlText));
}
}
Output
<Other Details>null</Other Details>
Exception in thread "main" org.json.JSONException: Misshaped close tag at 34 [character 35 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:568)
at org.json.XML.parse(XML.java:321)
at org.json.XML.parse(XML.java:443)
at org.json.XML.toJSONObject(XML.java:777)
at org.json.XML.toJSONObject(XML.java:863)
at org.json.XML.toJSONObject(XML.java:662)
at com.tutorialspoint.JsonDemo.main(JsonDemo.java:13)
Advertisements