如何在 Java 中从包含 ':' 、'[' 和 ']' 等字符的字符串创建 Json 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19487113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:41:20 来源:igfitidea点击:
How to create Json object from String containing characters like ':' ,'[' and ']' in Java
提问by DevCoder
I have one string from which I want to create one jsonobject
我有一个字符串,我想从中创建一个 jsonobject
import org.json.JSONObject;
JSONObject json=new JSONObject("{success=false, errorMessage=Application with appId : [randomAppId] not registered, errorCode=102}");
System.out.println("JSON:"+json.toString());
BUT right now I'm getting exception due to characters like :
,[
,]
which is inside the string.
但现在我得到的例外是由于喜欢的字符:
,[
,]
这是里面的字符串。
Stacktrace:
堆栈跟踪:
Exception in thread "main" org.json.JSONException: Expected a ',' or '}' at character 53
at org.json.JSONTokener.syntaxError(JSONTokener.java:410)
at org.json.JSONObject.<init>(JSONObject.java:222)
at org.json.JSONObject.<init>(JSONObject.java:402)
采纳答案by Henry
The problem is, that your string is not valid JSON. Try:
问题是,您的字符串不是有效的 JSON。尝试:
JSONObject json=new JSONObject("{\"success\":false, \"errorMessage\":\"Application with appId : [randomAppId] not registered\", \"errorCode\":102}");