如何从String中创建包含':','['和']'等字符的Json对象

时间:2013-10-21 05:53:06

标签: java json

我有一个字符串,我想从中创建一个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());

但是现在我因为字符串中的:[]这样的字符而出现异常。

堆栈跟踪:

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)

1 个答案:

答案 0 :(得分:5)

问题是,你的字符串是无效的JSON。尝试:

JSONObject json=new JSONObject("{\"success\":false, \"errorMessage\":\"Application with appId : [randomAppId] not registered\", \"errorCode\":102}");