Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i am getting data from restful api in String variable now i want to convert to JSON object but i am having problem while conversion it throws exception .Here is my code :

URL url = new URL("SOME URL");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");

BufferedReader br = new BufferedReader(new InputStreamReader(
        (conn.getInputStream())));

String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
    System.out.println(output);
}

conn.disconnect();


JSONObject jObject  = new JSONObject(output);
String projecname=(String) jObject.get("name");
System.out.print(projecname);

MY string contain

 {"data":{"name":"New Product","id":1,"description":"","is_active":true,"parent":{"id":0,"name":"All Projects"}}}

this is the string which i want in json but it shows me Exception in thread "main"

java.lang.NullPointerException
    at java.io.StringReader.<init>(Unknown Source)
    at org.json.JSONTokener.<init>(JSONTokener.java:83)
    at org.json.JSONObject.<init>(JSONObject.java:310)
    at Main.main(Main.java:37)
share|improve this question
add comment

3 Answers

up vote 2 down vote accepted

The name is present inside the data. You need to parse a JSON hierarchically to be able to fetch the data properly.

JSONObject jObject  = new JSONObject(output); // json
JSONObject data = jObject.getJSONObject("data"); // get data object
String projectname = data.getString("name"); // get the name from data.
share|improve this answer
add comment

Instead of JSONObject , you can use ObjectMapper to convert java object to json string

ObjectMapper mapper = new ObjectMapper();
String requestBean = mapper.writeValueAsString(yourObject);
share|improve this answer
add comment

You are getting NullPointerException as the "output" is null when the while loop ends. You can collect the output in some buffer and then use it, something like this-

    StringBuilder buffer = new StringBuilder();
    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
        buffer.append(output);
    }
    output = buffer.toString(); // now you have the output
    conn.disconnect();
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.