value(double) can write NaN and infinite values when lenient, as value(Number) does (#1093)

* Added test which shows that lenient JsonWriter fails writing infinite primitive doubles, but does not fail writing boxed doubles, as stated in #1090.

* Fixed JsonWriter#value(double) to write infinite and NaN values when lenient, as JsonWriter#value(Number) does. (fixes #1090)
This commit is contained in:
Mike 2017-05-31 19:50:45 +03:00 committed by inder123
parent 0aaef0fd1b
commit ada597e69a
2 changed files with 28 additions and 3 deletions

View File

@ -491,10 +491,10 @@ public class JsonWriter implements Closeable, Flushable {
* @return this writer.
*/
public JsonWriter value(double value) throws IOException {
if (Double.isNaN(value) || Double.isInfinite(value)) {
writeDeferredName();
if (!lenient && (Double.isNaN(value) || Double.isInfinite(value))) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
}
writeDeferredName();
beforeValue();
out.append(Double.toString(value));
return this;

View File

@ -16,11 +16,12 @@
package com.google.gson.stream;
import junit.framework.TestCase;
import java.io.IOException;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import junit.framework.TestCase;
@SuppressWarnings("resource")
public final class JsonWriterTest extends TestCase {
@ -213,6 +214,30 @@ public final class JsonWriterTest extends TestCase {
}
}
public void testNonFiniteDoublesWhenLenient() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.setLenient(true);
jsonWriter.beginArray();
jsonWriter.value(Double.NaN);
jsonWriter.value(Double.NEGATIVE_INFINITY);
jsonWriter.value(Double.POSITIVE_INFINITY);
jsonWriter.endArray();
assertEquals("[NaN,-Infinity,Infinity]", stringWriter.toString());
}
public void testNonFiniteBoxedDoublesWhenLenient() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.setLenient(true);
jsonWriter.beginArray();
jsonWriter.value(Double.valueOf(Double.NaN));
jsonWriter.value(Double.valueOf(Double.NEGATIVE_INFINITY));
jsonWriter.value(Double.valueOf(Double.POSITIVE_INFINITY));
jsonWriter.endArray();
assertEquals("[NaN,-Infinity,Infinity]", stringWriter.toString());
}
public void testDoubles() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);