mirror of
https://github.com/fankes/moshi.git
synced 2025-10-19 07:59:21 +08:00
Add writer value overload for boxed booleans.
Autoboxing resolves boxed longs and doubles to value(Number), but a boxed boolean would otherwise resolve to value(boolean) with an implicit call to booleanValue() which has the potential to throw NPEs.
This commit is contained in:
@@ -260,6 +260,13 @@ final class BufferedSinkJsonWriter extends JsonWriter {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override public JsonWriter value(Boolean value) throws IOException {
|
||||
if (value == null) {
|
||||
return nullValue();
|
||||
}
|
||||
return value(value.booleanValue());
|
||||
}
|
||||
|
||||
@Override public JsonWriter value(double value) throws IOException {
|
||||
if (Double.isNaN(value) || Double.isInfinite(value)) {
|
||||
throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
|
||||
|
@@ -228,6 +228,13 @@ public abstract class JsonWriter implements Closeable, Flushable {
|
||||
*/
|
||||
public abstract JsonWriter value(boolean value) throws IOException;
|
||||
|
||||
/**
|
||||
* Encodes {@code value}.
|
||||
*
|
||||
* @return this writer.
|
||||
*/
|
||||
public abstract JsonWriter value(Boolean value) throws IOException;
|
||||
|
||||
/**
|
||||
* Encodes {@code value}.
|
||||
*
|
||||
|
@@ -76,7 +76,7 @@ final class StandardJsonAdapters {
|
||||
}
|
||||
|
||||
@Override public void toJson(JsonWriter writer, Boolean value) throws IOException {
|
||||
writer.value(value);
|
||||
writer.value(value.booleanValue());
|
||||
}
|
||||
|
||||
@Override public String toString() {
|
||||
|
@@ -292,6 +292,17 @@ public final class BufferedSinkJsonWriterTest {
|
||||
assertThat(buffer.readUtf8()).isEqualTo("[true,false]");
|
||||
}
|
||||
|
||||
@Test public void boxedBooleans() throws IOException {
|
||||
Buffer buffer = new Buffer();
|
||||
JsonWriter jsonWriter = JsonWriter.of(buffer);
|
||||
jsonWriter.beginArray();
|
||||
jsonWriter.value((Boolean) true);
|
||||
jsonWriter.value((Boolean) false);
|
||||
jsonWriter.value((Boolean) null);
|
||||
jsonWriter.endArray();
|
||||
assertThat(buffer.readUtf8()).isEqualTo("[true,false,null]");
|
||||
}
|
||||
|
||||
@Test public void nulls() throws IOException {
|
||||
Buffer buffer = new Buffer();
|
||||
JsonWriter jsonWriter = JsonWriter.of(buffer);
|
||||
|
Reference in New Issue
Block a user