在 Java 中将字符串转换为 json 的问题

Issue with converting string to json in Java

我是 Java 的新手,我正在 Eclipse 中使用 Servlet 创建 Web 应用程序。 我想使用此代码将字符串转换为 JSON:

import org.json.JSONException; 
import org.json.JSONObject;

JSONObject jsonObject = null;
jsonObject = new JSONObject(STRING);

System.out.println(jsonObject.getString("PROPERTY_NAME"));

如果 STRING 等于 "{'status':0}" 并且 jsonObject.getString("status") 给我 0

但是我从 API 得到了回复,比如 "{"status":0}" 并且 jsonObject.getString("status") 给我错误,因为 jsonObject 是:

{}

错误是:

org.json.JSONException: JSONObject["status"] not found.

你有什么解决办法吗?

问题出在值而不是键上。我已经测试过了,它有效

JSONObject jsonObject = null;
jsonObject = new JSONObject("{\"status\":0}");
System.out.println(jsonObject.getInt("status"));

或这个

 JSONObject jsonObject = null;
 jsonObject = new JSONObject("{\"status\":'0'}");
 System.out.println(jsonObject.getString("status"));

您需要在 STRING 变量中转义双引号:

"{\"status\":0}"

您可以像那样以编程方式执行此操作(我们需要调用 toString(),因为 STRING 是 StringBuilder 的一个实例):

String escapedJsonStr = STRING.toString().replaceAll("\"", "\\"");

我可以用下面的例子帮助你...

for (String key: jsonObject.keySet()){ System.out.println(key); }

这将为您获取 JSON 中的一组密钥。

JSONObject json_array = args.optJSONObject(0);

Iterator keys = json_array.keys();

while( keys.hasNext() ) { String key = (String) keys.next(); System.out.println("Key: " + key); System.out.println("Value: " + json_array.get(key)); }

I recommend following the link for a thorough understanding of Java and JSON -- Example