问题
I have a String in java that might look like this:
String str = "Hello this is #David's first comment #excited"
I want to convert this string to a json object, but it throws an error when I use the below:
JSONObject json = new JSONObject(str);
I have found out that it throws an error due to the '#' symbol.
Is there any other way to convert the string to json, without much hassle ?
回答1:
The problem is not so much the '#' symbols; it's that you are trying to parse the string as if it's already JSON. You probably want something like this:
JSONObject json = new JSONObject();
json.put("firstString", str);
String jsonString = json.toString();
or, more briefly (if all you want is a quoted JSON string:
String jsonString = JSONObject.valueToString(str);
来源:https://stackoverflow.com/questions/11788664/how-do-i-convert-a-string-with-hashtags-to-json-in-java