简体   繁体   English

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

[英]How to create Json object from String containing characters like ':' ,'[' and ']' in Java

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)

The problem is, that your string is not valid JSON. 问题是,您的字符串不是有效的JSON。 Try: 尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM