Search code examples
javajsonorg.json

Convert string to json object giving error


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

Solution

  • 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:

    4. Objects

    An object structure is represented as a pair of curly brackets
    surrounding zero or more name/value pairs (or members). A name is a
    string. A single colon comes after each name, separating the name
    from the value. A single comma separates a value from a following
    name. The names within an object SHOULD be unique.

    You can preprocess you JSON before parsing it using String.replace()

    String s ="{name=Alex, sex=male}";
        
    JSONObject obj = new JSONObject(s.replace('=', ':'));
        
    System.out.println(obj.get("name"));
    

    Output:

    Alex
    

    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.