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:
- Import the required packages:
import org.json.JSONObject;
import org.json.JSONException;
- Create a
JSONObject
instance:
JSONObject json = new JSONObject();
- Add key-value pairs to the JSON object:
json.put("key", "value");
- 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);
}
}
Like this:
Like Loading...
Related
You must log in to post a comment.