Parsing an InputStream into a Json object and getting the value

Json answer:

{
    "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"
}

I use the one framework helper that we have. Framework returns the response as "InputStream". I want to get "pak_id" from this "InputStream". I tried with inputStreamObj.toString(), this does not work for me.

Method used:

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;
}

and

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();
}
+4
source share
3 answers

If you look at the documentation for InputStream , you will notice that it does not promise you that it will toStringpresent you the contents of the stream.

( , , , , , ), , , String, String.

String InputStream, IOUtils.toString apache commons-io.

+2

pak_id, :

InputStream is = ...
String line;
StringBuilder text = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while((line = reader.readLine()) != null) {
    text.append(line).append(" ");
}
String pakId = text.toString().replaceAll(".*\"pak_id\": \"([^\"]+)\".*", "$1");
0

, , ... :

JSONTokener tokener = new JSONTokener(new InputStreamReader(istream));
JSONObject result;
try {
    result = new JSONObject(tokener);
} catch (JSONException e) {
    // Handle me!
}
0

Source: https://habr.com/ru/post/1536424/


All Articles