Home > Software design >  Convert string to json object giving error
Convert string to json object giving error

Time:11-28

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

CodePudding user response:

The string you're assigning to the variable s is not valid JSON. Property names and properties should be separated by : instead of =, and double quotes should be used around strings and property names.

So the string in your example should be like this (with \ being used to escape the quote characters within the string quotes):

String s = "{\"name\":\"Alex\",\"sex\":\"male\"}";

CodePudding user response:

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.

CodePudding user response:

this fixes your problem.

String s ="{name:Alex, sex:male}";

CodePudding user response:

You should use : instead of =

String s = """{"name":"Alex","sex":"male"}"""; (Since Java 13 preview feature)

  • Related