I have a string which needs to be converted to JSONObject, I added the dependency, but I'm getting error, which I'm not able to figure out. I have the following dependency:
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20220924</version>
</dependency>
String s ="{name=Alex, sex=male}";
JSONObject obj = new JSONObject(s);
System.out.println(obj.get("name"));
I'm getting an exception:
org.json.JSONException: Expected a ':' after a key at line 5
The JSON you've provided is not valid because separator colon
:should be used a separator between a Key and a Value (not an equals sign).A quote from the standard The JavaScript Object Notation (JSON) Data Interchange Format:
You can preprocess you JSON before parsing it using
String.replace()Output:
Also, note that Org.json (as well as some other libraries like Gson) would take care of fixing missing double quotes
". But it would not be the case with libraries like Jackson.