Java JsonEncoding-class And Method Code Example


Here is an example of using the JsonEncoding class from the Apache Commons IO library to encode a JSON object to a string:

import org.apache.commons.io.output.StringBuilderWriter;
import org.json.JSONObject;
import org.json.JSONTokener;

String jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
JSONObject json = new JSONObject(new JSONTokener(jsonString));
StringBuilderWriter writer = new StringBuilderWriter();
json.write(writer, JsonEncoding.UTF8.getJavaName());
String encodedJson = writer.toString();

This code first creates a JSONObject from a string containing a JSON object. Then it creates a StringBuilderWriter and uses the json.write method with JsonEncoding.UTF8.getJavaName() to write the JSON object to the writer. Finally, it stores the result in the encodedJson variable.