Reputation: 401
I am trying to get nested JSON data from string JSON data using JSONObject and JSONArray. The code is compiling without any error but the result is coming Null rather than the string associated. If there is any alternate way to nest JSON string please suggest.
My code:
import java.io.*;
import java.net.*
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class A4 {
public static void main(String[] args){
String out,out1= null;
try{
URL a=new URL("URL");
HttpURLConnection b=(HttpURLConnection) a.openConnection();
b.setRequestMethod("GET");
b.setRequestProperty("Accept", "application/json");
BufferedReader c=new BufferedReader(new InputStreamReader(b.getInputStream()));
StringBuilder sb=new StringBuilder();
while((out=c.readLine())!=null){
sb.append(out);
out1=sb.toString();
}
c.close();
b.disconnect();
}catch (Exception e){
e.printStackTrace();
return;
}
JSONParser parser = new JSONParser();
try{
Object obj = parser.parse(out1);
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("Name");
System.out.println(name);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 606
Reputation: 374
Instead of using JSONParser to get the JSONObject you can directly use the following code
JSONObject jsonObj = new JSONObject(out1)
Upvotes: 0
Reputation: 658
try the below code i think it should work for you:
while((out=c.readLine())!=null){
sb=sb.append(out);
}
out1=sb.toString();
please let me know whether it's working for you or not?
Upvotes: 1