How do I convert a string with 'hashtags' to json in java?

岁酱吖の 提交于 2019-12-13 05:55:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!