Skip to main content
0 reactions

Convert JSON to String in Java – Quick and Easy Steps

json
Photo by RealToughCandy.com on Pexels.com

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:
Java
import org.json.JSONObject;
import org.json.JSONException;
  1. Create a JSONObject instance:
Java
JSONObject json = new JSONObject();
  1. Add key-value pairs to the JSON object:
Java
json.put("key", "value");
  1. Convert the JSONObject to a String:
Java
String jsonString = json.toString();

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

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

Advertisement

0 comments