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.
I note that your example code snippets are not sufficiently clear / complete to be able to tell exactly what you are doing. (In future, please provide a real MCVE rather than code snippets that don't make a lot of sense 1 ... and certainly can't be compiled and run.) But there is nothing to indicate that that code is the cause of the ParseException
.
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 .
To fix this, you are going to need to work out why the parser thinks your JSON is bad, and work back to the root cause of the badness.
1 - For example, why are you assigning a JSONParser
object to a variable of type Object
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.