Skip to content

Commit

Permalink
Add boxed boolean value() overload.
Browse files Browse the repository at this point in the history
When calling value() with a Boolean overload resolution would choose value(boolean) which would throw an NPE on null. The other boxed types are all numbers which would resolve to value(Number) and behave correctly.
  • Loading branch information
JakeWharton committed Apr 22, 2016
1 parent 0f66f4f commit 59edfc1
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,14 @@ private void put(JsonElement value) {
return this;
}

@Override public JsonWriter value(Boolean value) throws IOException {
if (value == null) {
return nullValue();
}
put(new JsonPrimitive(value));
return this;
}

@Override public JsonWriter value(double value) throws IOException {
if (!isLenient() && (Double.isNaN(value) || Double.isInfinite(value))) {
throw new IllegalArgumentException("JSON forbids NaN and infinities: " + value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,10 +162,6 @@ public Boolean read(JsonReader in) throws IOException {
}
@Override
public void write(JsonWriter out, Boolean value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
out.value(value);
}
};
Expand Down
15 changes: 15 additions & 0 deletions gson/src/main/java/com/google/gson/stream/JsonWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,21 @@ public JsonWriter value(boolean value) throws IOException {
return this;
}

/**
* 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;
}

/**
* Encodes {@code value}.
*
Expand Down
11 changes: 11 additions & 0 deletions gson/src/test/java/com/google/gson/stream/JsonWriterTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,17 @@ public void testBooleans() throws IOException {
assertEquals("[true,false]", stringWriter.toString());
}

public void testBoxedBooleans() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.value((Boolean) true);
jsonWriter.value((Boolean) false);
jsonWriter.value((Boolean) null);
jsonWriter.endArray();
assertEquals("[true,false,null]", stringWriter.toString());
}

public void testNulls() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
Expand Down

0 comments on commit 59edfc1

Please sign in to comment.