Convert JSON to String in Java – Quick and Easy Steps

Learn how to convert JSON to String in Java using the JSONObject class and the toString() method. Follow the simple steps for a successful conversion.

You can convert a JSON object to a string in Java using the following steps:

  1. Import the required packages:
import org.json.JSONObject;
import org.json.JSONException;
  1. Create a JSONObject instance:
JSONObject json = new JSONObject();
  1. Add key-value pairs to the JSON object:
json.put("key", "value");
  1. Convert the JSONObject to a String:
String jsonString = json.toString();

Finally, you can use the jsonString variable to store, send or process the JSON data. Example:

import org.json.JSONObject;
import org.json.JSONException;

public class JsonToString {
   public static void main(String[] args) {
      JSONObject json = new JSONObject();
      try {
         json.put("name", "John Doe");
         json.put("age", 30);
         json.put("city", "New York");
      } catch (JSONException e) {
         e.printStackTrace();
      }
      String jsonString = json.toString();
      System.out.println(jsonString);
   }
}

Up ↑

%d bloggers like this: