Philo Philo - 5 months ago 32
JSON Question

Java string convert to JSON object for http POST

I am trying to recreate a http Post request to consume a webAPI. I originally created it in C# and got it to work. But the java analogous seems to be giving me a bit of ...

my input string consists of parameters expected by the webapi.

String input = "{" +
"\"UserID\":xxx," +
"\"UserPsw\":\"yyy," +
"\"ApiFunction\":zzz," +
"\"DppName\":aaaa," +
"\"DppVersion\":Latest, " +
"\"ClearData\"ftfdgfdgfdg fdgfdgfd 4354534," +
"\"ResultType\":JSON \"}";

Now I downloaded the JSON-simple jar file from:-

and imported it in my libraries folder for the java project.

then for my class, I imported the following:-

import org.json.simple.JSONObject;

The intention is to convert my 'input' string into a JSON onbject as such:-

JSONObject jsonObject = new JSONObject(input);

but I am getting an error that says:-

cannot find symbol
symbol: constructor JSONObject(java.lang.String)
location: class org.json.simple.JSONObject

what am I doing wrong?

The reason I want to convert it into a JSON object, is because my webapi expects a certain format for a string...

{"UserID":xx,"UserPsw":yyy,"ApiFunction":zzz,"DppName":aaaa,"DppVersion":Latest, "ClearData":ftfdgfdgfdg fdgfdgfd 4354534,"ResultType":JSON "}

however my java string input is formatted as:-

{"UserID":"xx","UserPsw":"yyy","ApiFunction":"zzz","DppName":"aaaa","DppVersion":"Latest", "ClearData":"ftfdgfdgfdg fdgfdgf 4354534","ResultType":"JSON"}

which is different than how C# sends it as a class object with quotes only around property names and not around values.


According to the docs

there is no constructor that accepts a String as parameter. You may think about converting it to a Map which would make it clearer and less error-prone.

 HashMap<String,String> newMap = new HashMap<>();
 //... the rest of your attributes
 JSONObject jsonObject = new JSONObject(newMap);

As proposed by 'Mappan' you could use the JSONParser, as well:

try {
  JSONParser parser = new JSONParser();
  JSONObject json = (JSONObject) parser.parse(stringToParse);
} catch (org.json.simple.parser.ParsingException e) {

Taken from : How to convert String to JSONObject in Java