Ask Your Question
0

In Java, what is the method to parse a JSON response from a REST request when the root element's name is not provided?

asked 2023-06-04 04:22:29 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-04 04:34:01 +0000

bukephalos gravatar image

If the root element's name is not provided in a JSON response from a REST request in Java, you can use the JSONTokener class to handle the parsing process. Here's an example code snippet:

import org.json.JSONObject;
import org.json.JSONTokener;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class JsonParser {

    public static void main(String[] args) {
        try {
            URL url = new URL("http://example.com"); // replace with your API endpoint
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(url.openStream()));
            StringBuilder builder = new StringBuilder();
            String input;
            while ((input = reader.readLine()) != null) {
                builder.append(input);
            }
            JSONObject json = (JSONObject) new JSONTokener(builder.toString()).nextValue();
            System.out.println(json.toString(2)); // prints the JSON response in a readable format
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In this code, we first create a URL object and open a stream to read the JSON response. We then create a StringBuilder to store the input from the stream, and read the data into the builder using the BufferedReader class.

Next, we create a new JSONTokener object with the string contents of the builder, and call the nextValue() method to parse the JSON response into a JSONObject. We can print this JSONObject to the console using the toString() method, along with a pretty-printing format using the toString(int indentFactor) method.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-04 04:22:29 +0000

Seen: 10 times

Last updated: Jun 04 '23