Send JSON data in Java

Here's an example Java code snippet that sends JSON data as a string:

import org.json.JSONObject;

public class SendJSONData {

    public static void main(String[] args) throws Exception {

        // create a JSON object
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("name", "John");
        jsonObj.put("age", 30);
        jsonObj.put("city", "New York");

        // convert JSON object to string
        String jsonStr = jsonObj.toString();

        // specify the URL to send the JSON data to
        String urlStr = "";

        // create a URL object
        URL url = new URL(urlStr);

        // create an HTTP connection
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Content-Type", "application/json");

        // send the JSON data as a string
        OutputStream os = conn.getOutputStream();

        // read the response from the server
        int responseCode = conn.getResponseCode();
        System.out.println("Response code: " + responseCode);

        // close the connection and output stream

In this example, we create a JSON object using the JSONObject class from the org.json package, and then convert it to a string using the toString() method. We then specify the URL to send the JSON data to, and create an HTTP connection using the HttpURLConnection class. We set the request method to POST, and set the content type header to application/json.

We then send the JSON data as a string using the output stream of the HTTP connection, and read the response code from the server. Finally, we close the connection and output stream.