package org.json; /* Copyright (c) 2006 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import org.json.util.ALStack; import java.io.Closeable; import java.io.IOException; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * JSONWriter provides a quick and convenient way of producing JSON text. * The texts produced strictly conform to JSON syntax rules. No whitespace is * added, so the results are ready for transmission or storage. Each instance of * JSONWriter can produce one JSON text. *
* A JSONWriter instance provides a value method for appending
* values to the
* text, and a key
* method for adding keys before values in objects. There are array
* and endArray methods that make and bound array values, and
* object and endObject methods which make and bound
* object values. All of these methods return the JSONWriter instance,
* permitting a cascade style. For example,
* new JSONWriter(myWriter)
* .object()
* .key("JSON")
* .value("Hello, World!")
* .endObject(); which writes
* {"JSON":"Hello, World!"}
*
* The first method called must be array or object.
* There are no methods for adding commas or colons. JSONWriter adds them for
* you. Objects and arrays can be nested arbitrarily deep.
*
* This can sometimes be easier than using a JSONObject to build a string.
* @author JSON.org
* @version 2016-08-04
*/
public class JSONWriter implements Closeable {
private static final int initdepth = 16;
/**
* The comma flag determines if a comma should be output before the next
* value.
*/
private boolean comma;
/**
* The current mode. Values:
* 'a' (array),
* 'd' (done),
* 'i' (initial),
* 'k' (key),
* 'o' (object).
*/
protected char mode;
/**
* The object/array stack, for duplicate key detection.
* Arrays are represented as null elements, while objects are
* represented as sets of key strings.
*/
private final ALStack
* Warning: This method assumes that the data structure is acyclical.
*
* @param value
* The value to be written
* @param writer
* Writes the serialized JSON
* @param
* Warning: This method assumes that the data structure is acyclical.
*
* @param value
* The value to be written
* @param writer
* Writes the serialized JSON
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @param
* Warning: This method assumes that the data structure is acyclical.
*
* @param value
* The JSONString to be written
* @param writer
* Writes the serialized JSON
* @param
* Warning: This method assumes that the data structure is acyclical.
*
* @param value
* The JSONString to be written
* @param writer
* Writes the serialized JSON
* @param
* Warning: This method assumes that the data structure is acyclical.
*
* @param bean
* The bean to be written
* @param writer
* Writes the serialized JSON
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @param
* Warning: This method assumes that the data structure is acyclical.
*
* @param map
* The Map to be written
* @param writer
* Writes the serialized JSON
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @param
* Warning: This method assumes that the data structure is acyclical.
*
* @param collection
* The Iterable to be written
* @param writer
* Writes the serialized JSON
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @param
* Warning: This method assumes that the data structure is acyclical.
*
* @param array
* The array to be written
* @param writer
* Writes the serialized JSON
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @param
* Warning: This method assumes that the data structure is acyclical.
*
* @param object
* The JSONObject to be written
* @param writer
* Writes the serialized JSON
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @param
* Warning: This method assumes that the data structure is acyclical.
*
* @param array
* The JSONArray to be written
* @param writer
* Writes the serialized JSON
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @param endArray will be appended to this array. The
* endArray method must be called to mark the array's end.
* @return this
* @throws JSONException If the nesting is too deep, or if the object is
* started in the wrong place (for example as a key or after the end of the
* outermost array or object).
*/
public JSONWriter array() throws JSONException {
if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') {
this.push(false);
try {
this.prepValue();
this.writer.append('[');
} catch (IOException e) {
throw new JSONException(e);
}
this.comma = false;
return this;
}
throw new JSONException("Misplaced array.");
}
/**
* End something.
* @param mode Mode
* @param c Closing character
* @return this
* @throws JSONException If unbalanced.
*/
private JSONWriter end(char mode, char c) throws JSONException {
if (this.mode != mode) {
throw new JSONException(mode == 'a'
? "Misplaced endArray."
: "Misplaced endObject.");
}
this.pop(mode);
try {
this.writer.append(c);
} catch (IOException e) {
throw new JSONException(e);
}
this.comma = true;
return this;
}
/**
* End an array. This method most be called to balance calls to
* array.
* @return this
* @throws JSONException If incorrectly nested.
*/
public JSONWriter endArray() throws JSONException {
return this.end('a', ']');
}
/**
* End an object. This method most be called to balance calls to
* object.
* @return this
* @throws JSONException If incorrectly nested.
*/
public JSONWriter endObject() throws JSONException {
return this.end('k', '}');
}
/**
* Append a key. The key will be associated with the next value. In an
* object, every value must be preceded by a key.
* @param string A key string.
* @return this
* @throws JSONException If the key is out of place. For example, keys
* do not belong in arrays or if the key is null.
*/
public JSONWriter key(String string) throws JSONException {
if (string == null) {
throw new JSONException("Null key.");
}
if (this.mode == 'k') {
try {
if(!this.stack.peek().add(string)) {
throw new JSONException("Duplicate key \"" + string + "\"");
}
if (this.comma) {
this.writer.append(',');
}
writeString(string, this.writer).append(':');
this.comma = false;
this.mode = 'o';
return this;
} catch (IOException e) {
throw new JSONException(e);
}
}
throw new JSONException("Misplaced key.");
}
/**
* Begin appending a new object. All keys and values until the balancing
* endObject will be appended to this object. The
* endObject method must be called to mark the object's end.
* @return this
* @throws JSONException If the nesting is too deep, or if the object is
* started in the wrong place (for example as a key or after the end of the
* outermost array or object).
*/
public JSONWriter object() throws JSONException {
if (this.mode == 'i') {
this.mode = 'o';
}
if (this.mode == 'o' || this.mode == 'a') {
try {
this.prepValue();
this.writer.append('{');
} catch (IOException e) {
throw new JSONException(e);
}
this.push(true);
this.comma = false;
return this;
}
throw new JSONException("Misplaced object.");
}
/**
* Pop an array or object scope.
* @param c The scope to close.
* @throws JSONException If nesting is wrong.
*/
private void pop(char c) throws JSONException {
if (this.stack.isEmpty()) {
throw new JSONException("Nesting error.");
}
char m = this.stack.pop() == null ? 'a' : 'k';
if (m != c) {
throw new JSONException("Nesting error.");
}
this.mode = this.stack.isEmpty()
? 'd'
: this.stack.peek() == null
? 'a'
: 'k';
}
/**
* Push an object or array scope.
*
* @param obj {@code true} to indicate an Object, otherwise {@code false}
* to indicate an Array
* @throws JSONException If nesting is too deep.
*/
private void push(boolean obj) throws JSONException {
this.stack.push(obj ? new HashSetnull value.
* @return this
* @throws JSONException there was a problem writing the null value
*/
public JSONWriter nullValue() throws JSONException {
this.prepValue();
writeNull(this.writer);
return this;
}
/**
* Append either the value true or the value
* false.
* @param b A boolean.
* @return this
* @throws JSONException there was a problem writing the boolean value
*/
public JSONWriter value(boolean b) throws JSONException {
String string = Boolean.toString(b);
try {
this.prepValue();
this.writer.append(string);
return this;
} catch (IOException e) {
throw new JSONException(e);
}
}
/**
* Append a double value.
* @param d A double.
* @return this
* @throws JSONException If the number is not finite.
*/
public JSONWriter value(double d) throws JSONException {
this.prepValue();
writeDouble(d, this.writer);
return this;
}
/**
* Append a long value.
* @param l A long.
* @return this
* @throws JSONException there was a problem writing the long value
*/
public JSONWriter value(long l) throws JSONException {
String string = Long.toString(l);
try {
this.prepValue();
this.writer.append(string);
return this;
} catch (IOException e) {
throw new JSONException(e);
}
}
/**
* Append an object value.
* @param object The object to appendString. It can be null, or a Boolean, Number,
* String, JSONObject, or JSONArray, or an object that implements JSONString.
* @return this
* @throws JSONException If the value is out of sequence.
*/
public JSONWriter value(Object object) throws JSONException {
this.prepValue();
writeValue(object, this.writer);
return this;
}
/**
* Append a sequence of values into an array.
*
* @param values The objects to appendString. They can be null, or a Boolean, Number,
* String, JSONObject, or JSONArray, or an object that implements JSONString.
* @return this
* @throws JSONException If a value is out of place. For example, a value
* occurs where a key is expected.
*/
public JSONWriter values(Iterable> values) throws JSONException {
for(Object obj : values) {
this.prepValue();
writeValue(obj, this.writer);
}
return this;
}
/**
* Append a sequence of keys and values in an object.
* The key will be associated with the corresponding value. In an
* object, every value must be associated with a key.
*
* @param kvPairs The objects to appendString. The values can be null, or a Boolean,
* Number, String, JSONObject, or JSONArray, or an object that implements
* JSONString.
* @return this
* @throws JSONException If a key or value is out of place. For example, keys
* do not belong in arrays or if the key is null.
*/
public JSONWriter entries(Map, ?> kvPairs) throws JSONException {
for(Entry, ?> entry : kvPairs.entrySet()) {
this.key(String.valueOf(entry.getKey()));
this.prepValue();
writeValue(entry.getValue(), this.writer);
}
return this;
}
/**
* Asserts the JSON writer is finished, and close any underlying
* {@code Closeable} writer.
*
* @throws IOException the writer cannot be closed
*/
@Override
public void close() throws IOException {
if(!this.stack.isEmpty()) {
throw new IOException("JSON stack is not empty");
}
if(writer instanceof Closeable) {
((Closeable)writer).close();
}
}
// -- static writer methods
// 120 spaces, divides by 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, ...
private static final String PADDING_SPACES = makePaddingSpaces();
private static final int PADDING_LENGTH = 120;
private static String makePaddingSpaces() {
char[] padding = new char[PADDING_LENGTH];
Arrays.fill(padding, ' ');
return String.valueOf(padding);
}
/**
* Indent by the given number of spaces.
*
* @param indent
* the number of character to indent.
* @param writer
* the writer.
* @param