Question

It seems like there're 2 ways to write the content of a JSON object to a writer. I can either do

myWriter.write(myJSONObj.toString());

Or

myJSONObj.write(myWriter);

Is there any reason why anyone would choose one way over the other?

Was it helpful?

Solution

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());
  1. Creates a StringWriter.
  2. Passes the writer to write(Writer writer, int indentFactor, int indent).
  3. The JSON content get written to the writer.
  4. The content of the writer is converted via StringWriter#toString().
  5. The final string get written to myWriter.

The second approach:

myJSONObj.write(myWriter);
  1. Passes the writer to write(Writer writer, int indentFactor, int indent).
  2. The JSON content get written to the writer.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top