According to the source code:
public String toString() {
try {
return this.toString(0);
} catch (Exception e) {
return null;
}
}
public String toString(int indentFactor) throws JSONException {
StringWriter w = new StringWriter();
synchronized (w.getBuffer()) {
return this.write(w, indentFactor, 0).toString();
}
}
public Writer write(Writer writer) throws JSONException {
return this.write(writer, 0, 0);
}
so basically, the first approach:
myWriter.write(myJSONObj.toString());
- Creates a
StringWriter
. - Passes the writer to
write(Writer writer, int indentFactor, int indent)
. - The JSON content get written to the writer.
- The content of the writer is converted via
StringWriter#toString()
. - The final string get written to
myWriter
.
The second approach:
myJSONObj.write(myWriter);
- Passes the writer to
write(Writer writer, int indentFactor, int indent)
. - The JSON content get written to the writer.