Esempio n. 1
0
  /**
   * Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace
   * is added.
   *
   * <p>Warning: This method assumes that the data structure is acyclical.
   *
   * @return The writer.
   * @throws JSONException
   */
  Writer write(Writer writer, int indentFactor, int indent) throws JSONException {
    try {
      boolean commanate = false;
      final int length = this.length();
      Iterator keys = this.keys();
      writer.write('{');

      if (length == 1) {
        Object key = keys.next();
        writer.write(quote(key.toString()));
        writer.write(':');
        if (indentFactor > 0) {
          writer.write(' ');
        }
        writeValue(writer, this.map.get(key), indentFactor, indent);
      } else if (length != 0) {
        final int newindent = indent + indentFactor;
        while (keys.hasNext()) {
          Object key = keys.next();
          if (commanate) {
            writer.write(',');
          }
          if (indentFactor > 0) {
            writer.write('\n');
          }
          indent(writer, newindent);
          writer.write(quote(key.toString()));
          writer.write(':');
          if (indentFactor > 0) {
            writer.write(' ');
          }
          writeValue(writer, this.map.get(key), indentFactor, newindent);
          commanate = true;
        }
        if (indentFactor > 0) {
          writer.write('\n');
        }
        indent(writer, indent);
      }
      writer.write('}');
      return writer;
    } catch (IOException exception) {
      throw new JSONException(exception);
    }
  }