我有一个像这样的 json 响应字符串
string result ={"username": "sdrG", "size": 965204, "filename": "test.doc"}
从中尝试获取尺寸值
为此,我使用 JSON 对象转换 JSON 字符串获取键值
JSONObject jObject = new JSONObject(result); // json
String size = (String) jObject.get("size");
System.out.println(size);
但是他的代码对我不起作用
org.json.JSONException: JSONObject["size"] not found.
最佳答案
经过一些修改,你的代码对我有用:-
public static void main(String[] args) throws DatatypeConfigurationException {
String result ="{\"username\": \"sdrG\", \"size\": 965204, \"filename\": \"test.doc\"}";
JSONObject jObject = new JSONObject(result); // json
String size = String.valueOf((Integer) jObject.get("size"));
System.out.println(size);
}
使用过:-
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
如果你的 Json 存储在 StringBuffer 中,你可以这样做:-
JSONObject jObject = new JSONObject(result.toString());
关于java - 无法使用 JSON 解析 Json String 来获取键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31869427/