如何在Java中将带有'hashtags'的字符串转换为json? [英] How do I convert a string with 'hashtags' to json in java?
本文介绍了如何在Java中将带有'hashtags'的字符串转换为json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Java中有一个字符串,看起来可能像这样:
I have a String in java that might look like this:
String str = "Hello this is #David's first comment #excited"
我想将此字符串转换为json对象,但是当我使用以下代码时会引发错误:
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);
我发现由于#"符号而引发错误.
还有没有其他麻烦将字符串转换为json的其他方法?
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 ?
推荐答案
问题不仅仅在于'#'符号;这是因为您尝试解析该字符串,就好像它已经是JSON.您可能想要这样的东西:
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();
或更简单地说(如果您想要的只是带引号的JSON字符串:
or, more briefly (if all you want is a quoted JSON string:
String jsonString = JSONObject.valueToString(str);
这篇关于如何在Java中将带有'hashtags'的字符串转换为json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文