Java String to JSON conversion

java, json, web-services

Solution

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");

Problem

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) ```

Original source