[java] Java String to JSON conversion

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)

This question is related to java json web-services

The answer is


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

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

ObjectMapper mapper = new ObjectMapper();
String requestBean = mapper.writeValueAsString(yourObject);

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to web-services

How do I POST XML data to a webservice with Postman? How to send json data in POST request using C# org.springframework.web.client.HttpClientErrorException: 400 Bad Request How to call a REST web service API from JavaScript? The request was rejected because no multipart boundary was found in springboot Generating Request/Response XML from a WSDL How to send a POST request using volley with string body? How to send post request to the below post method using postman rest client How to pass a JSON array as a parameter in URL Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw