I have a JSON-formatted String
that has a singular key-value pair and a Map
consisting of various String
-typed keys and values within it, as follows:
"{"Key":"value","Map":{"key1":"val1","key2":"val2",...}}"
What I want to do is convert this String
into a JSONObject
(because I have other code that can easily interpret a JSONObject
). My first instinct was to use a parser (JSONParser
) like the code snippet below...
JSONParser parser = new JSONParser();
Object o = new JSONParser();
o = (JSONObject) parser.parse(jsonStr);
JSONObject j = (JSONObject) o;
…but I got a ParseException
instead of the convenient JSONObject
. Why is that? Should I be treating the String
differently, since it has a Map
inside of it? Or am I doing something beyond the capabilities of a JSONParser
?
... but I got a
ParseException
instead of the convenientJSONObject
. Why is that?
If you got a ParseException
, that means that what you think is JSON is (in fact) not valid JSON. It is not a problem with your parsing code or the JSONObject
parser. It is either a problem with the way the (supposed) JSON was produced in the first place, or with "channel" by which it reached the code that was supposed to parse it.
Should I be treating the string differently, since it has a map inside of it?
Nope.
Or am I doing something beyond the capabilities of a
JSONParser
?
Nope. A JSON parser can cope with any JSON provided that it is well-formed.
You provided only code fragments, and you didn't provide a stacktrace or the actual input JSON. That makes it impossible to diagnose your problem for you.
So, to fix this, you are going to need to work out why the parser thinks your actual JSON is bad, and work back to the root cause of the badness.