fix up write/save, add indent= option

This commit is contained in:
Ben Fry
2015-04-25 03:06:13 -04:00
parent dfec4490fb
commit 1c189ab5f3
2 changed files with 65 additions and 33 deletions

View File

@@ -36,7 +36,6 @@ SOFTWARE.
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
@@ -1094,18 +1093,39 @@ public class JSONArray {
// }
protected boolean save(OutputStream output) {
return save(PApplet.createWriter(output));
}
// protected boolean save(OutputStream output) {
// return write(PApplet.createWriter(output), null);
// }
public boolean save(File file, String options) {
return save(PApplet.createWriter(file));
return write(PApplet.createWriter(file), options);
}
public boolean save(PrintWriter output) {
output.print(format(2));
public boolean write(PrintWriter output) {
return write(output, null);
}
public boolean write(PrintWriter output, String options) {
int indentFactor = 2;
if (options != null) {
String[] opts = PApplet.split(options, ',');
for (String opt : opts) {
if (opt.equals("compact")) {
indentFactor = -1;
} else if (opt.startsWith("indent=")) {
indentFactor = PApplet.parseInt(opt.substring(7), -2);
if (indentFactor == -2) {
throw new IllegalArgumentException("Could not read a number from " + opt);
}
} else {
System.err.println("Ignoring " + opt);
}
}
}
output.print(format(indentFactor));
output.flush();
return true;
}
@@ -1139,27 +1159,26 @@ public class JSONArray {
public String format(int indentFactor) {
StringWriter sw = new StringWriter();
synchronized (sw.getBuffer()) {
return this.write(sw, indentFactor, 0).toString();
return this.writeInternal(sw, indentFactor, 0).toString();
}
}
/**
* Write the contents of the JSONArray as JSON text to a writer. For
* compactness, no whitespace is added.
* <p>
* Warning: This method assumes that the data structure is acyclic.
*
* @return The writer.
*/
protected Writer write(Writer writer) {
return this.write(writer, -1, 0);
}
// /**
// * Write the contents of the JSONArray as JSON text to a writer. For
// * compactness, no whitespace is added.
// * <p>
// * Warning: This method assumes that the data structure is acyclic.
// *
// * @return The writer.
// */
// protected Writer write(Writer writer) {
// return this.write(writer, -1, 0);
// }
/**
* Write the contents of the JSONArray as JSON text to a writer. For
* compactness, no whitespace is added.
* Write the contents of the JSONArray as JSON text to a writer.
* <p>
* Warning: This method assumes that the data structure is acyclic.
*
@@ -1171,7 +1190,7 @@ public class JSONArray {
* @return The writer.
* @throws JSONException
*/
protected Writer write(Writer writer, int indentFactor, int indent) {
protected Writer writeInternal(Writer writer, int indentFactor, int indent) {
try {
boolean commanate = false;
int length = this.size();