2010-08-26 10:44:02 +02:00
|
|
|
/*
|
|
|
|
* Copyright (C) 2010 Google Inc.
|
|
|
|
*
|
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
* you may not use this file except in compliance with the License.
|
|
|
|
* You may obtain a copy of the License at
|
|
|
|
*
|
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
*
|
|
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
* See the License for the specific language governing permissions and
|
|
|
|
* limitations under the License.
|
|
|
|
*/
|
|
|
|
|
|
|
|
package com.google.gson.stream;
|
|
|
|
|
|
|
|
import java.io.Closeable;
|
2012-06-30 04:46:26 +02:00
|
|
|
import java.io.Flushable;
|
2010-08-26 10:44:02 +02:00
|
|
|
import java.io.IOException;
|
|
|
|
import java.io.Writer;
|
2022-01-28 20:26:28 +01:00
|
|
|
import java.math.BigDecimal;
|
|
|
|
import java.math.BigInteger;
|
2022-05-12 23:23:14 +02:00
|
|
|
import java.util.*;
|
2022-01-28 20:26:28 +01:00
|
|
|
import java.util.concurrent.atomic.AtomicInteger;
|
|
|
|
import java.util.concurrent.atomic.AtomicLong;
|
|
|
|
import java.util.regex.Pattern;
|
2012-08-14 23:32:18 +02:00
|
|
|
|
|
|
|
import static com.google.gson.stream.JsonScope.DANGLING_NAME;
|
|
|
|
import static com.google.gson.stream.JsonScope.EMPTY_ARRAY;
|
|
|
|
import static com.google.gson.stream.JsonScope.EMPTY_DOCUMENT;
|
|
|
|
import static com.google.gson.stream.JsonScope.EMPTY_OBJECT;
|
|
|
|
import static com.google.gson.stream.JsonScope.NONEMPTY_ARRAY;
|
|
|
|
import static com.google.gson.stream.JsonScope.NONEMPTY_DOCUMENT;
|
|
|
|
import static com.google.gson.stream.JsonScope.NONEMPTY_OBJECT;
|
2010-08-26 10:44:02 +02:00
|
|
|
|
|
|
|
/**
|
2016-01-18 21:07:33 +01:00
|
|
|
* Writes a JSON (<a href="http://www.ietf.org/rfc/rfc7159.txt">RFC 7159</a>)
|
2010-08-26 10:44:02 +02:00
|
|
|
* encoded value to a stream, one token at a time. The stream includes both
|
|
|
|
* literal values (strings, numbers, booleans and nulls) as well as the begin
|
|
|
|
* and end delimiters of objects and arrays.
|
|
|
|
*
|
|
|
|
* <h3>Encoding JSON</h3>
|
|
|
|
* To encode your data as JSON, create a new {@code JsonWriter}. Each JSON
|
|
|
|
* document must contain one top-level array or object. Call methods on the
|
|
|
|
* writer as you walk the structure's contents, nesting arrays and objects as
|
|
|
|
* necessary:
|
|
|
|
* <ul>
|
|
|
|
* <li>To write <strong>arrays</strong>, first call {@link #beginArray()}.
|
|
|
|
* Write each of the array's elements with the appropriate {@link #value}
|
|
|
|
* methods or by nesting other arrays and objects. Finally close the array
|
|
|
|
* using {@link #endArray()}.
|
|
|
|
* <li>To write <strong>objects</strong>, first call {@link #beginObject()}.
|
|
|
|
* Write each of the object's properties by alternating calls to
|
|
|
|
* {@link #name} with the property's value. Write property values with the
|
|
|
|
* appropriate {@link #value} method or by nesting other objects or arrays.
|
|
|
|
* Finally close the object using {@link #endObject()}.
|
|
|
|
* </ul>
|
|
|
|
*
|
|
|
|
* <h3>Example</h3>
|
|
|
|
* Suppose we'd like to encode a stream of messages such as the following: <pre> {@code
|
|
|
|
* [
|
|
|
|
* {
|
|
|
|
* "id": 912345678901,
|
|
|
|
* "text": "How do I stream JSON in Java?",
|
|
|
|
* "geo": null,
|
|
|
|
* "user": {
|
|
|
|
* "name": "json_newb",
|
|
|
|
* "followers_count": 41
|
|
|
|
* }
|
|
|
|
* },
|
|
|
|
* {
|
|
|
|
* "id": 912345678902,
|
|
|
|
* "text": "@json_newb just use JsonWriter!",
|
|
|
|
* "geo": [50.454722, -104.606667],
|
|
|
|
* "user": {
|
|
|
|
* "name": "jesse",
|
|
|
|
* "followers_count": 2
|
|
|
|
* }
|
|
|
|
* }
|
|
|
|
* ]}</pre>
|
|
|
|
* This code encodes the above structure: <pre> {@code
|
|
|
|
* public void writeJsonStream(OutputStream out, List<Message> messages) throws IOException {
|
|
|
|
* JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));
|
2015-09-27 03:10:00 +02:00
|
|
|
* writer.setIndent(" ");
|
2010-08-26 10:44:02 +02:00
|
|
|
* writeMessagesArray(writer, messages);
|
|
|
|
* writer.close();
|
|
|
|
* }
|
|
|
|
*
|
|
|
|
* public void writeMessagesArray(JsonWriter writer, List<Message> messages) throws IOException {
|
|
|
|
* writer.beginArray();
|
|
|
|
* for (Message message : messages) {
|
|
|
|
* writeMessage(writer, message);
|
|
|
|
* }
|
|
|
|
* writer.endArray();
|
|
|
|
* }
|
|
|
|
*
|
|
|
|
* public void writeMessage(JsonWriter writer, Message message) throws IOException {
|
|
|
|
* writer.beginObject();
|
|
|
|
* writer.name("id").value(message.getId());
|
|
|
|
* writer.name("text").value(message.getText());
|
|
|
|
* if (message.getGeo() != null) {
|
|
|
|
* writer.name("geo");
|
|
|
|
* writeDoublesArray(writer, message.getGeo());
|
|
|
|
* } else {
|
|
|
|
* writer.name("geo").nullValue();
|
|
|
|
* }
|
|
|
|
* writer.name("user");
|
|
|
|
* writeUser(writer, message.getUser());
|
|
|
|
* writer.endObject();
|
|
|
|
* }
|
|
|
|
*
|
|
|
|
* public void writeUser(JsonWriter writer, User user) throws IOException {
|
|
|
|
* writer.beginObject();
|
|
|
|
* writer.name("name").value(user.getName());
|
|
|
|
* writer.name("followers_count").value(user.getFollowersCount());
|
|
|
|
* writer.endObject();
|
|
|
|
* }
|
|
|
|
*
|
|
|
|
* public void writeDoublesArray(JsonWriter writer, List<Double> doubles) throws IOException {
|
|
|
|
* writer.beginArray();
|
|
|
|
* for (Double value : doubles) {
|
|
|
|
* writer.value(value);
|
|
|
|
* }
|
|
|
|
* writer.endArray();
|
|
|
|
* }}</pre>
|
|
|
|
*
|
|
|
|
* <p>Each {@code JsonWriter} may be used to write a single JSON stream.
|
|
|
|
* Instances of this class are not thread safe. Calls that would result in a
|
|
|
|
* malformed JSON string will fail with an {@link IllegalStateException}.
|
2010-10-28 01:53:09 +02:00
|
|
|
*
|
2010-08-26 10:44:02 +02:00
|
|
|
* @author Jesse Wilson
|
2010-10-28 01:53:09 +02:00
|
|
|
* @since 1.6
|
2010-08-26 10:44:02 +02:00
|
|
|
*/
|
2012-06-30 04:46:26 +02:00
|
|
|
public class JsonWriter implements Closeable, Flushable {
|
2010-08-26 10:44:02 +02:00
|
|
|
|
2022-01-28 20:26:28 +01:00
|
|
|
// Syntax as defined by https://datatracker.ietf.org/doc/html/rfc8259#section-6
|
|
|
|
private static final Pattern VALID_JSON_NUMBER_PATTERN = Pattern.compile("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][-+]?[0-9]+)?");
|
|
|
|
|
2012-04-12 15:24:37 +02:00
|
|
|
/*
|
2016-01-18 21:07:33 +01:00
|
|
|
* From RFC 7159, "All Unicode characters may be placed within the
|
2012-04-12 15:24:37 +02:00
|
|
|
* quotation marks except for the characters that must be escaped:
|
|
|
|
* quotation mark, reverse solidus, and the control characters
|
|
|
|
* (U+0000 through U+001F)."
|
|
|
|
*
|
|
|
|
* We also escape '\u2028' and '\u2029', which JavaScript interprets as
|
|
|
|
* newline characters. This prevents eval() from failing with a syntax
|
|
|
|
* error. http://code.google.com/p/google-gson/issues/detail?id=341
|
|
|
|
*/
|
|
|
|
private static final String[] REPLACEMENT_CHARS;
|
|
|
|
private static final String[] HTML_SAFE_REPLACEMENT_CHARS;
|
|
|
|
static {
|
|
|
|
REPLACEMENT_CHARS = new String[128];
|
|
|
|
for (int i = 0; i <= 0x1f; i++) {
|
|
|
|
REPLACEMENT_CHARS[i] = String.format("\\u%04x", (int) i);
|
|
|
|
}
|
|
|
|
REPLACEMENT_CHARS['"'] = "\\\"";
|
|
|
|
REPLACEMENT_CHARS['\\'] = "\\\\";
|
|
|
|
REPLACEMENT_CHARS['\t'] = "\\t";
|
|
|
|
REPLACEMENT_CHARS['\b'] = "\\b";
|
|
|
|
REPLACEMENT_CHARS['\n'] = "\\n";
|
|
|
|
REPLACEMENT_CHARS['\r'] = "\\r";
|
|
|
|
REPLACEMENT_CHARS['\f'] = "\\f";
|
|
|
|
HTML_SAFE_REPLACEMENT_CHARS = REPLACEMENT_CHARS.clone();
|
|
|
|
HTML_SAFE_REPLACEMENT_CHARS['<'] = "\\u003c";
|
|
|
|
HTML_SAFE_REPLACEMENT_CHARS['>'] = "\\u003e";
|
|
|
|
HTML_SAFE_REPLACEMENT_CHARS['&'] = "\\u0026";
|
|
|
|
HTML_SAFE_REPLACEMENT_CHARS['='] = "\\u003d";
|
|
|
|
HTML_SAFE_REPLACEMENT_CHARS['\''] = "\\u0027";
|
|
|
|
}
|
|
|
|
|
2010-08-26 10:44:02 +02:00
|
|
|
/** The output data, containing at most one top-level array or object. */
|
|
|
|
private final Writer out;
|
|
|
|
|
2012-08-14 23:32:18 +02:00
|
|
|
private int[] stack = new int[32];
|
|
|
|
private int stackSize = 0;
|
2010-08-26 10:44:02 +02:00
|
|
|
{
|
2012-08-14 23:32:18 +02:00
|
|
|
push(EMPTY_DOCUMENT);
|
2010-08-26 10:44:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* A string containing a full set of spaces for a single level of
|
|
|
|
* indentation, or null for no pretty printing.
|
|
|
|
*/
|
|
|
|
private String indent;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* The name/value separator; either ":" or ": ".
|
|
|
|
*/
|
|
|
|
private String separator = ":";
|
|
|
|
|
2010-08-28 10:18:13 +02:00
|
|
|
private boolean lenient;
|
|
|
|
|
2010-09-02 02:15:23 +02:00
|
|
|
private boolean htmlSafe;
|
|
|
|
|
2011-09-30 09:08:44 +02:00
|
|
|
private String deferredName;
|
|
|
|
|
|
|
|
private boolean serializeNulls = true;
|
|
|
|
|
2010-08-26 10:44:02 +02:00
|
|
|
/**
|
|
|
|
* Creates a new instance that writes a JSON-encoded stream to {@code out}.
|
|
|
|
* For best performance, ensure {@link Writer} is buffered; wrapping in
|
|
|
|
* {@link java.io.BufferedWriter BufferedWriter} if necessary.
|
|
|
|
*/
|
|
|
|
public JsonWriter(Writer out) {
|
|
|
|
if (out == null) {
|
|
|
|
throw new NullPointerException("out == null");
|
|
|
|
}
|
|
|
|
this.out = out;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Sets the indentation string to be repeated for each level of indentation
|
|
|
|
* in the encoded document. If {@code indent.isEmpty()} the encoded document
|
|
|
|
* will be compact. Otherwise the encoded document will be more
|
|
|
|
* human-readable.
|
|
|
|
*
|
|
|
|
* @param indent a string containing only whitespace.
|
|
|
|
*/
|
2011-09-30 08:26:46 +02:00
|
|
|
public final void setIndent(String indent) {
|
2010-09-02 11:29:26 +02:00
|
|
|
if (indent.length() == 0) {
|
2010-08-26 10:44:02 +02:00
|
|
|
this.indent = null;
|
|
|
|
this.separator = ":";
|
|
|
|
} else {
|
|
|
|
this.indent = indent;
|
|
|
|
this.separator = ": ";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2010-08-28 10:18:13 +02:00
|
|
|
/**
|
|
|
|
* Configure this writer to relax its syntax rules. By default, this writer
|
|
|
|
* only emits well-formed JSON as specified by <a
|
2016-01-18 21:07:33 +01:00
|
|
|
* href="http://www.ietf.org/rfc/rfc7159.txt">RFC 7159</a>. Setting the writer
|
2010-08-28 10:18:13 +02:00
|
|
|
* to lenient permits the following:
|
|
|
|
* <ul>
|
|
|
|
* <li>Top-level values of any type. With strict writing, the top-level
|
|
|
|
* value must be an object or an array.
|
|
|
|
* <li>Numbers may be {@link Double#isNaN() NaNs} or {@link
|
|
|
|
* Double#isInfinite() infinities}.
|
|
|
|
* </ul>
|
|
|
|
*/
|
2011-09-30 08:26:46 +02:00
|
|
|
public final void setLenient(boolean lenient) {
|
2010-08-28 10:18:13 +02:00
|
|
|
this.lenient = lenient;
|
|
|
|
}
|
|
|
|
|
2010-09-02 02:15:23 +02:00
|
|
|
/**
|
|
|
|
* Returns true if this writer has relaxed syntax rules.
|
|
|
|
*/
|
|
|
|
public boolean isLenient() {
|
|
|
|
return lenient;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Configure this writer to emit JSON that's safe for direct inclusion in HTML
|
|
|
|
* and XML documents. This escapes the HTML characters {@code <}, {@code >},
|
|
|
|
* {@code &} and {@code =} before writing them to the stream. Without this
|
|
|
|
* setting, your XML/HTML encoder should replace these characters with the
|
|
|
|
* corresponding escape sequences.
|
|
|
|
*/
|
2011-09-30 08:26:46 +02:00
|
|
|
public final void setHtmlSafe(boolean htmlSafe) {
|
2010-09-02 02:15:23 +02:00
|
|
|
this.htmlSafe = htmlSafe;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns true if this writer writes JSON that's safe for inclusion in HTML
|
|
|
|
* and XML documents.
|
|
|
|
*/
|
2011-09-30 08:26:46 +02:00
|
|
|
public final boolean isHtmlSafe() {
|
2010-09-02 02:15:23 +02:00
|
|
|
return htmlSafe;
|
|
|
|
}
|
|
|
|
|
2011-09-30 09:08:44 +02:00
|
|
|
/**
|
|
|
|
* Sets whether object members are serialized when their value is null.
|
|
|
|
* This has no impact on array elements. The default is true.
|
|
|
|
*/
|
|
|
|
public final void setSerializeNulls(boolean serializeNulls) {
|
|
|
|
this.serializeNulls = serializeNulls;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns true if object members are serialized when their value is null.
|
|
|
|
* This has no impact on array elements. The default is true.
|
|
|
|
*/
|
|
|
|
public final boolean getSerializeNulls() {
|
|
|
|
return serializeNulls;
|
|
|
|
}
|
|
|
|
|
2022-05-12 23:23:14 +02:00
|
|
|
/**
|
|
|
|
* Insert a comment at the current location.
|
|
|
|
* May create a new line.
|
|
|
|
*/
|
|
|
|
public JsonWriter comment(String comment) throws IOException {
|
|
|
|
if (comment == null || comment.isBlank()) return this;
|
|
|
|
String[] parts = comment.split("\n");
|
|
|
|
if (indent == null) {
|
|
|
|
out.append("/* ").append(String.join(" / ", parts)).append(" */");
|
|
|
|
} else {
|
|
|
|
for (String s : parts) {
|
|
|
|
out.append("// ").append(s);
|
|
|
|
newline();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
2010-08-26 10:44:02 +02:00
|
|
|
/**
|
|
|
|
* Begins encoding a new array. Each call to this method must be paired with
|
|
|
|
* a call to {@link #endArray}.
|
|
|
|
*
|
|
|
|
* @return this writer.
|
|
|
|
*/
|
|
|
|
public JsonWriter beginArray() throws IOException {
|
2011-09-30 09:08:44 +02:00
|
|
|
writeDeferredName();
|
2019-09-18 19:33:49 +02:00
|
|
|
return open(EMPTY_ARRAY, '[');
|
2010-08-26 10:44:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Ends encoding the current array.
|
|
|
|
*
|
|
|
|
* @return this writer.
|
|
|
|
*/
|
|
|
|
public JsonWriter endArray() throws IOException {
|
2019-09-18 19:33:49 +02:00
|
|
|
return close(EMPTY_ARRAY, NONEMPTY_ARRAY, ']');
|
2010-08-26 10:44:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Begins encoding a new object. Each call to this method must be paired
|
|
|
|
* with a call to {@link #endObject}.
|
|
|
|
*
|
|
|
|
* @return this writer.
|
|
|
|
*/
|
|
|
|
public JsonWriter beginObject() throws IOException {
|
2011-09-30 09:08:44 +02:00
|
|
|
writeDeferredName();
|
2019-09-18 19:33:49 +02:00
|
|
|
return open(EMPTY_OBJECT, '{');
|
2010-08-26 10:44:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Ends encoding the current object.
|
|
|
|
*
|
|
|
|
* @return this writer.
|
|
|
|
*/
|
|
|
|
public JsonWriter endObject() throws IOException {
|
2019-09-18 19:33:49 +02:00
|
|
|
return close(EMPTY_OBJECT, NONEMPTY_OBJECT, '}');
|
2010-08-26 10:44:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Enters a new scope by appending any necessary whitespace and the given
|
|
|
|
* bracket.
|
|
|
|
*/
|
2019-09-18 19:33:49 +02:00
|
|
|
private JsonWriter open(int empty, char openBracket) throws IOException {
|
2016-01-18 21:07:33 +01:00
|
|
|
beforeValue();
|
2012-08-14 23:32:18 +02:00
|
|
|
push(empty);
|
2010-08-26 10:44:02 +02:00
|
|
|
out.write(openBracket);
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Closes the current scope by appending any necessary whitespace and the
|
|
|
|
* given bracket.
|
|
|
|
*/
|
2019-09-18 19:33:49 +02:00
|
|
|
private JsonWriter close(int empty, int nonempty, char closeBracket)
|
2010-08-26 10:44:02 +02:00
|
|
|
throws IOException {
|
2012-08-14 23:32:18 +02:00
|
|
|
int context = peek();
|
2010-08-26 10:44:02 +02:00
|
|
|
if (context != nonempty && context != empty) {
|
2012-08-14 23:32:18 +02:00
|
|
|
throw new IllegalStateException("Nesting problem.");
|
2010-08-26 10:44:02 +02:00
|
|
|
}
|
2011-09-30 09:08:44 +02:00
|
|
|
if (deferredName != null) {
|
|
|
|
throw new IllegalStateException("Dangling name: " + deferredName);
|
|
|
|
}
|
2010-08-26 10:44:02 +02:00
|
|
|
|
2012-08-14 23:32:18 +02:00
|
|
|
stackSize--;
|
2010-08-26 10:44:02 +02:00
|
|
|
if (context == nonempty) {
|
|
|
|
newline();
|
|
|
|
}
|
|
|
|
out.write(closeBracket);
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
2012-08-14 23:32:18 +02:00
|
|
|
private void push(int newTop) {
|
|
|
|
if (stackSize == stack.length) {
|
2019-03-02 23:49:05 +01:00
|
|
|
stack = Arrays.copyOf(stack, stackSize * 2);
|
2012-08-14 23:32:18 +02:00
|
|
|
}
|
|
|
|
stack[stackSize++] = newTop;
|
|
|
|
}
|
|
|
|
|
2010-08-26 10:44:02 +02:00
|
|
|
/**
|
|
|
|
* Returns the value on the top of the stack.
|
|
|
|
*/
|
2012-08-14 23:32:18 +02:00
|
|
|
private int peek() {
|
|
|
|
if (stackSize == 0) {
|
2012-02-12 21:42:16 +01:00
|
|
|
throw new IllegalStateException("JsonWriter is closed.");
|
|
|
|
}
|
2012-08-14 23:32:18 +02:00
|
|
|
return stack[stackSize - 1];
|
2010-08-26 10:44:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Replace the value on the top of the stack with the given value.
|
|
|
|
*/
|
2012-08-14 23:32:18 +02:00
|
|
|
private void replaceTop(int topOfStack) {
|
|
|
|
stack[stackSize - 1] = topOfStack;
|
2010-08-26 10:44:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Encodes the property name.
|
|
|
|
*
|
|
|
|
* @param name the name of the forthcoming value. May not be null.
|
|
|
|
* @return this writer.
|
|
|
|
*/
|
|
|
|
public JsonWriter name(String name) throws IOException {
|
|
|
|
if (name == null) {
|
|
|
|
throw new NullPointerException("name == null");
|
|
|
|
}
|
2011-09-30 09:08:44 +02:00
|
|
|
if (deferredName != null) {
|
|
|
|
throw new IllegalStateException();
|
|
|
|
}
|
2012-08-14 23:32:18 +02:00
|
|
|
if (stackSize == 0) {
|
2012-02-12 21:42:16 +01:00
|
|
|
throw new IllegalStateException("JsonWriter is closed.");
|
|
|
|
}
|
2011-09-30 09:08:44 +02:00
|
|
|
deferredName = name;
|
2010-08-26 10:44:02 +02:00
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
2011-09-30 09:08:44 +02:00
|
|
|
private void writeDeferredName() throws IOException {
|
|
|
|
if (deferredName != null) {
|
|
|
|
beforeName();
|
|
|
|
string(deferredName);
|
|
|
|
deferredName = null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2010-08-26 10:44:02 +02:00
|
|
|
/**
|
|
|
|
* Encodes {@code value}.
|
|
|
|
*
|
|
|
|
* @param value the literal string value, or null to encode a null literal.
|
|
|
|
* @return this writer.
|
|
|
|
*/
|
|
|
|
public JsonWriter value(String value) throws IOException {
|
|
|
|
if (value == null) {
|
|
|
|
return nullValue();
|
|
|
|
}
|
2011-09-30 09:08:44 +02:00
|
|
|
writeDeferredName();
|
2016-01-18 21:07:33 +01:00
|
|
|
beforeValue();
|
2010-08-26 10:44:02 +02:00
|
|
|
string(value);
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
2015-07-19 21:46:26 +02:00
|
|
|
/**
|
|
|
|
* Writes {@code value} directly to the writer without quoting or
|
|
|
|
* escaping.
|
|
|
|
*
|
|
|
|
* @param value the literal string value, or null to encode a null literal.
|
|
|
|
* @return this writer.
|
|
|
|
*/
|
|
|
|
public JsonWriter jsonValue(String value) throws IOException {
|
|
|
|
if (value == null) {
|
|
|
|
return nullValue();
|
|
|
|
}
|
|
|
|
writeDeferredName();
|
2016-01-18 21:07:33 +01:00
|
|
|
beforeValue();
|
2015-07-19 21:46:26 +02:00
|
|
|
out.append(value);
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
2010-08-26 10:44:02 +02:00
|
|
|
/**
|
|
|
|
* Encodes {@code null}.
|
|
|
|
*
|
|
|
|
* @return this writer.
|
|
|
|
*/
|
|
|
|
public JsonWriter nullValue() throws IOException {
|
2011-09-30 09:08:44 +02:00
|
|
|
if (deferredName != null) {
|
|
|
|
if (serializeNulls) {
|
|
|
|
writeDeferredName();
|
|
|
|
} else {
|
|
|
|
deferredName = null;
|
|
|
|
return this; // skip the name and the value
|
|
|
|
}
|
|
|
|
}
|
2016-01-18 21:07:33 +01:00
|
|
|
beforeValue();
|
2010-08-26 10:44:02 +02:00
|
|
|
out.write("null");
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Encodes {@code value}.
|
|
|
|
*
|
|
|
|
* @return this writer.
|
|
|
|
*/
|
|
|
|
public JsonWriter value(boolean value) throws IOException {
|
2011-09-30 09:08:44 +02:00
|
|
|
writeDeferredName();
|
2016-01-18 21:07:33 +01:00
|
|
|
beforeValue();
|
2010-08-26 10:44:02 +02:00
|
|
|
out.write(value ? "true" : "false");
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
2016-04-23 01:50:10 +02:00
|
|
|
/**
|
|
|
|
* Encodes {@code value}.
|
|
|
|
*
|
|
|
|
* @return this writer.
|
|
|
|
*/
|
|
|
|
public JsonWriter value(Boolean value) throws IOException {
|
|
|
|
if (value == null) {
|
|
|
|
return nullValue();
|
|
|
|
}
|
|
|
|
writeDeferredName();
|
|
|
|
beforeValue();
|
|
|
|
out.write(value ? "true" : "false");
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
2010-08-26 10:44:02 +02:00
|
|
|
/**
|
|
|
|
* Encodes {@code value}.
|
|
|
|
*
|
|
|
|
* @param value a finite value. May not be {@link Double#isNaN() NaNs} or
|
|
|
|
* {@link Double#isInfinite() infinities}.
|
|
|
|
* @return this writer.
|
2022-01-28 20:26:28 +01:00
|
|
|
* @throws IllegalArgumentException if the value is NaN or Infinity and this writer is
|
|
|
|
* not {@link #setLenient(boolean) lenient}.
|
2010-08-26 10:44:02 +02:00
|
|
|
*/
|
|
|
|
public JsonWriter value(double value) throws IOException {
|
2017-05-31 18:50:45 +02:00
|
|
|
writeDeferredName();
|
|
|
|
if (!lenient && (Double.isNaN(value) || Double.isInfinite(value))) {
|
2010-08-26 10:44:02 +02:00
|
|
|
throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
|
|
|
|
}
|
2016-01-18 21:07:33 +01:00
|
|
|
beforeValue();
|
2010-08-26 10:44:02 +02:00
|
|
|
out.append(Double.toString(value));
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Encodes {@code value}.
|
|
|
|
*
|
|
|
|
* @return this writer.
|
|
|
|
*/
|
|
|
|
public JsonWriter value(long value) throws IOException {
|
2011-09-30 09:08:44 +02:00
|
|
|
writeDeferredName();
|
2016-01-18 21:07:33 +01:00
|
|
|
beforeValue();
|
2010-08-26 10:44:02 +02:00
|
|
|
out.write(Long.toString(value));
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2022-01-28 20:26:28 +01:00
|
|
|
* Returns whether the {@code toString()} of {@code c} can be trusted to return
|
|
|
|
* a valid JSON number.
|
|
|
|
*/
|
|
|
|
private static boolean isTrustedNumberType(Class<? extends Number> c) {
|
|
|
|
// Note: Don't consider LazilyParsedNumber trusted because it could contain
|
|
|
|
// an arbitrary malformed string
|
|
|
|
return c == Integer.class || c == Long.class || c == Double.class || c == Float.class || c == Byte.class || c == Short.class
|
|
|
|
|| c == BigDecimal.class || c == BigInteger.class || c == AtomicInteger.class || c == AtomicLong.class;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Encodes {@code value}. The value is written by directly writing the {@link Number#toString()}
|
|
|
|
* result to JSON. Implementations must make sure that the result represents a valid JSON number.
|
2010-08-26 10:44:02 +02:00
|
|
|
*
|
|
|
|
* @param value a finite value. May not be {@link Double#isNaN() NaNs} or
|
|
|
|
* {@link Double#isInfinite() infinities}.
|
|
|
|
* @return this writer.
|
2022-01-28 20:26:28 +01:00
|
|
|
* @throws IllegalArgumentException if the value is NaN or Infinity and this writer is
|
|
|
|
* not {@link #setLenient(boolean) lenient}; or if the {@code toString()} result is not a
|
|
|
|
* valid JSON number.
|
2010-08-26 10:44:02 +02:00
|
|
|
*/
|
|
|
|
public JsonWriter value(Number value) throws IOException {
|
|
|
|
if (value == null) {
|
|
|
|
return nullValue();
|
|
|
|
}
|
|
|
|
|
2011-09-30 09:08:44 +02:00
|
|
|
writeDeferredName();
|
2010-08-26 10:44:02 +02:00
|
|
|
String string = value.toString();
|
2022-01-28 20:26:28 +01:00
|
|
|
if (string.equals("-Infinity") || string.equals("Infinity") || string.equals("NaN")) {
|
|
|
|
if (!lenient) {
|
|
|
|
throw new IllegalArgumentException("Numeric values must be finite, but was " + string);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
Class<? extends Number> numberClass = value.getClass();
|
|
|
|
// Validate that string is valid before writing it directly to JSON output
|
|
|
|
if (!isTrustedNumberType(numberClass) && !VALID_JSON_NUMBER_PATTERN.matcher(string).matches()) {
|
|
|
|
throw new IllegalArgumentException("String created by " + numberClass + " is not a valid JSON number: " + string);
|
|
|
|
}
|
2010-08-26 10:44:02 +02:00
|
|
|
}
|
2022-01-28 20:26:28 +01:00
|
|
|
|
2016-01-18 21:07:33 +01:00
|
|
|
beforeValue();
|
2010-08-26 10:44:02 +02:00
|
|
|
out.append(string);
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Ensures all buffered data is written to the underlying {@link Writer}
|
|
|
|
* and flushes that writer.
|
|
|
|
*/
|
2022-02-18 03:40:40 +01:00
|
|
|
@Override public void flush() throws IOException {
|
2012-08-14 23:32:18 +02:00
|
|
|
if (stackSize == 0) {
|
2012-02-12 21:42:16 +01:00
|
|
|
throw new IllegalStateException("JsonWriter is closed.");
|
|
|
|
}
|
2010-08-26 10:44:02 +02:00
|
|
|
out.flush();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Flushes and closes this writer and the underlying {@link Writer}.
|
|
|
|
*
|
|
|
|
* @throws IOException if the JSON document is incomplete.
|
|
|
|
*/
|
2022-02-18 03:40:40 +01:00
|
|
|
@Override public void close() throws IOException {
|
2010-08-26 10:44:02 +02:00
|
|
|
out.close();
|
|
|
|
|
2012-08-14 23:32:18 +02:00
|
|
|
int size = stackSize;
|
|
|
|
if (size > 1 || size == 1 && stack[size - 1] != NONEMPTY_DOCUMENT) {
|
2010-08-26 10:44:02 +02:00
|
|
|
throw new IOException("Incomplete document");
|
|
|
|
}
|
2012-08-14 23:32:18 +02:00
|
|
|
stackSize = 0;
|
2010-08-26 10:44:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
private void string(String value) throws IOException {
|
2012-04-12 15:24:37 +02:00
|
|
|
String[] replacements = htmlSafe ? HTML_SAFE_REPLACEMENT_CHARS : REPLACEMENT_CHARS;
|
2019-09-18 19:33:49 +02:00
|
|
|
out.write('\"');
|
2012-04-12 15:24:37 +02:00
|
|
|
int last = 0;
|
|
|
|
int length = value.length();
|
|
|
|
for (int i = 0; i < length; i++) {
|
2010-08-26 10:44:02 +02:00
|
|
|
char c = value.charAt(i);
|
2012-04-12 15:24:37 +02:00
|
|
|
String replacement;
|
|
|
|
if (c < 128) {
|
|
|
|
replacement = replacements[c];
|
|
|
|
if (replacement == null) {
|
|
|
|
continue;
|
2010-08-28 10:18:13 +02:00
|
|
|
}
|
2012-04-12 15:24:37 +02:00
|
|
|
} else if (c == '\u2028') {
|
|
|
|
replacement = "\\u2028";
|
|
|
|
} else if (c == '\u2029') {
|
|
|
|
replacement = "\\u2029";
|
|
|
|
} else {
|
|
|
|
continue;
|
2010-08-26 10:44:02 +02:00
|
|
|
}
|
2012-04-12 15:24:37 +02:00
|
|
|
if (last < i) {
|
|
|
|
out.write(value, last, i - last);
|
|
|
|
}
|
|
|
|
out.write(replacement);
|
|
|
|
last = i + 1;
|
|
|
|
}
|
|
|
|
if (last < length) {
|
|
|
|
out.write(value, last, length - last);
|
2010-08-26 10:44:02 +02:00
|
|
|
}
|
2019-09-18 19:33:49 +02:00
|
|
|
out.write('\"');
|
2010-08-26 10:44:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
private void newline() throws IOException {
|
|
|
|
if (indent == null) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-09-18 19:33:49 +02:00
|
|
|
out.write('\n');
|
2012-08-14 23:32:18 +02:00
|
|
|
for (int i = 1, size = stackSize; i < size; i++) {
|
2010-08-26 10:44:02 +02:00
|
|
|
out.write(indent);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Inserts any necessary separators and whitespace before a name. Also
|
|
|
|
* adjusts the stack to expect the name's value.
|
|
|
|
*/
|
|
|
|
private void beforeName() throws IOException {
|
2012-08-14 23:32:18 +02:00
|
|
|
int context = peek();
|
|
|
|
if (context == NONEMPTY_OBJECT) { // first in object
|
2010-08-26 10:44:02 +02:00
|
|
|
out.write(',');
|
2012-08-14 23:32:18 +02:00
|
|
|
} else if (context != EMPTY_OBJECT) { // not in an object!
|
|
|
|
throw new IllegalStateException("Nesting problem.");
|
2010-08-26 10:44:02 +02:00
|
|
|
}
|
|
|
|
newline();
|
2012-08-14 23:32:18 +02:00
|
|
|
replaceTop(DANGLING_NAME);
|
2010-08-26 10:44:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Inserts any necessary separators and whitespace before a literal value,
|
|
|
|
* inline array, or inline object. Also adjusts the stack to expect either a
|
|
|
|
* closing bracket or another element.
|
|
|
|
*/
|
2012-02-12 21:42:16 +01:00
|
|
|
@SuppressWarnings("fallthrough")
|
2016-01-18 21:07:33 +01:00
|
|
|
private void beforeValue() throws IOException {
|
2010-08-26 10:44:02 +02:00
|
|
|
switch (peek()) {
|
2012-02-12 21:42:16 +01:00
|
|
|
case NONEMPTY_DOCUMENT:
|
|
|
|
if (!lenient) {
|
|
|
|
throw new IllegalStateException(
|
|
|
|
"JSON must have only one top-level value.");
|
|
|
|
}
|
|
|
|
// fall-through
|
2010-08-26 10:44:02 +02:00
|
|
|
case EMPTY_DOCUMENT: // first in document
|
2012-08-14 23:32:18 +02:00
|
|
|
replaceTop(NONEMPTY_DOCUMENT);
|
2010-08-26 10:44:02 +02:00
|
|
|
break;
|
|
|
|
|
|
|
|
case EMPTY_ARRAY: // first in array
|
2012-08-14 23:32:18 +02:00
|
|
|
replaceTop(NONEMPTY_ARRAY);
|
2010-08-26 10:44:02 +02:00
|
|
|
newline();
|
|
|
|
break;
|
|
|
|
|
|
|
|
case NONEMPTY_ARRAY: // another in array
|
|
|
|
out.append(',');
|
|
|
|
newline();
|
|
|
|
break;
|
|
|
|
|
|
|
|
case DANGLING_NAME: // value for name
|
|
|
|
out.append(separator);
|
2012-08-14 23:32:18 +02:00
|
|
|
replaceTop(NONEMPTY_OBJECT);
|
2010-08-26 10:44:02 +02:00
|
|
|
break;
|
|
|
|
|
|
|
|
default:
|
2012-08-14 23:32:18 +02:00
|
|
|
throw new IllegalStateException("Nesting problem.");
|
2010-08-26 10:44:02 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|