Java: How to convert JSONObject to String

In Java, a JSONObject is an unordered collection of name/value pairs. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object.

A JSONObject has several methods such as get, opt and toString. If you have a JSONObject , you can easily convert it into a String using toString method.

JSONObject myobject = new JSONObject().put("JSON", "Hello, World!");

myobject.toString();

And if you want to get a specific value, you can use:

jsonObject.getString("msg");

or Integer value

jsonObject.getInt("codeNum");

Alternatively, You can try GSON converter, to get the exact conversion like json.stringify

val jsonString:String = jsonObject.toString()
val gson:Gson = GsonBuilder().setPrettyPrinting().create()
val json:JsonElement = gson.fromJson(jsonString,JsonElement.class)
val jsonInString:String= gson.toJson(json)
println(jsonInString)

If you absolutely need JACKSON, you can try:

JSONObject object = ...;
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(object);
Click to rate this post!
[Total: 13 Average: 4.8]

Leave a Comment