Reputation: 587
I'm trying to parse this following JSON string to java.
{"Stdout":"Hello World\nThis is Sara","Stderr":"exit status 124"}
This string is dynamic and the content can be different as in,
{"Stdout":"Hello World\nThis is Sara","Stderr":""}
or
{"Stdout":"","Stderr":"exit status 124"}
I'm using the following tutorial and instead of the file I'm adding my String in it.
So I created this code to simply print what "Stdout"
and "Stderr"
have to say:
public void parsed(String str) {
JSONParser parser=new JSONParser();
try {
Object obj = parser.parse(str);
JSONObject jsonObject = (JSONObject) obj;
JSONArray out = (JSONArray) jsonObject.get("Stdout");
Iterator<String> iterator = out.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// loop array
JSONArray err = (JSONArray) jsonObject.get("Stderr");
Iterator<String> iterator2 = err.iterator();
while (iterator2.hasNext()) {
System.out.println(iterator2.next());
}
} catch (ParseException e) {
e.printStackTrace();
}
}
I'm getting the following result. And I have tried each and every possible solution that I found on Stack Overflow and other sites.
java.lang.String cannot be cast to org.json.simple.JSONArray
Upvotes: 0
Views: 55
Reputation: 221
The conversions of stdout
and stderr
are wrong. They're both a String
instead of a JSONArray
. Try this:
Change: JSONArray out = (JSONArray) jsonObject.get("Stdout");
To: String stdout= (String) jsonObject.get("Stdout");
And print that String and see what happens.
Upvotes: 1