【发布时间】:2014-05-28 05:37:14
【问题描述】:
响应json:
{
"filename": "vcops-6.0.0-MPforAWS-1.1-1695068.pak",
"links": [
{
"rel": "pak_information",
"href": "https://<IP>:443/casa/upgrade/cluster/pak/MPforAWS-600/information"
},
{
"rel": "pak_file_information",
"href": "https://<IP>:443/casa/upgrade/slice/pak/MPforAWS-600/file_information"
},
{
"rel": "pak_cluster_status",
"href": "https://<IP>:443/casa/upgrade/cluster/pak/MPforAWS-600/status"
}
],
"pak_id": "MPforAWS-600"
}
我正在使用我们现有框架的一个助手。框架将响应返回为“InputStream”。
我想从这个“InputStream”中获取“pak_id”。我试过 inputStreamObj.toString() 这对我不起作用。
我使用的方法是:
private String getPakId(InputStream uploadResponse) {
String pakId = null;
try {
String responseString = readInputStream(uploadResponse);
JSONObject jObj = new JSONObject(responseString);
pakId = jObj.getString("pak_id").trim();
Reporter.log("Pak id is=" + pakId, true);
} catch (Exception e) {
Reporter.log("Error in getting pak_id " + e.getMessage(), true);
}
return pakId;
}
和
private String readInputStream(InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "UTF-8"));
String tmp;
StringBuilder sb = new StringBuilder();
while ((tmp = reader.readLine()) != null) {
sb.append(tmp).append("\n");
}
if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '\n') {
sb.setLength(sb.length() - 1);
}
reader.close();
return sb.toString();
}
【问题讨论】:
-
你当前的代码是什么?
-
您必须从 InputStream 中读取字符串,然后使用 JSON 库对其进行解析。
-
JSONObject jObj = new JSONObject(response.toString()); pakId = jObj.getString("pak_id").trim();
-
问题重复。试试这个解决方案:stackoverflow.com/a/47265988/1264496