23

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)
Mitaksh Gupta
  • 1,029
  • 6
  • 24
  • 50
Junaid Akhtar
  • 317
  • 1
  • 3
  • 13

4 Answers4

31

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.

Note: This example uses the org.json.JSONObject class and not org.json.simple.JSONObject.


As "Matthew" mentioned in the comments that he is using org.json.simple.JSONObject, I'm adding my comment details in the answer.

Try to use the org.json.JSONObject instead. But then if you can't change your JSON library, you can refer to this example which uses the same library as yours and check the how to read a json part from it.

Sample from the link provided:

JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
Rahul
  • 44,383
  • 11
  • 84
  • 103
  • 3
    My `org.json.simple.JSONObject` does not have a constructor for String, only a default contructor and one that takes a Map? – Matthew Moisen Mar 21 '14 at 00:54
  • @MatthewMoisen - Try to use the [`org.json.JSONObject`](http://www.json.org/javadoc/org/json/JSONObject.html) instead. But then if you can't change your JSON library, you can refer [this example](http://www.mkyong.com/java/json-simple-example-read-and-write-json/) which uses the same library as yours and check the how to read a json part from it. Should be fairly useful to you :) – Rahul Mar 21 '14 at 05:13
2

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();
Sudhanshu Umalkar
  • 4,174
  • 1
  • 23
  • 33
1

Converting the String to JsonNode using ObjectMapper object :

ObjectMapper mapper = new ObjectMapper();

// For text string
JsonNode = mapper.readValue(mapper.writeValueAsString("Text-string"), JsonNode.class)

// For Array String
JsonNode = mapper.readValue("[\"Text-Array\"]"), JsonNode.class)

// For Json String 
String json = "{\"id\" : \"1\"}";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser jsonParser = factory.createParser(json);
JsonNode node = mapper.readTree(jsonParser);
Rahul Chauhan
  • 1,487
  • 1
  • 11
  • 13
0

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

ObjectMapper mapper = new ObjectMapper();
String requestBean = mapper.writeValueAsString(yourObject);
Prithvipal Singh
  • 511
  • 4
  • 9
  • 23