Support booleans as strings in stream binding. Remove support for interpreting "1" as true.

Interpreting '1' as true was not backwards compatible.
This commit is contained in:
Jesse Wilson 2011-10-23 21:41:30 +00:00
parent 052c9ce0ce
commit 0340e01f98
4 changed files with 16 additions and 7 deletions

View File

@ -131,11 +131,8 @@ public final class JsonPrimitive extends JsonElement {
if (isBoolean()) {
return getAsBooleanWrapper().booleanValue();
} else {
// Check to see if the value (as a String) is either "true" (ignore case) or "1".
// If so then we will assume that it is true; otherwise, false.
// The "1" case is for parsing JSON that assume bits as booleans (i.e. 0 and 1).
String stringValue = getAsString();
return Boolean.parseBoolean(stringValue) || "1".equals(stringValue);
// Check to see if the value as a String is "true" in any case.
return Boolean.parseBoolean(getAsString());
}
}

View File

@ -114,6 +114,9 @@ public final class TypeAdapters {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
} else if (reader.peek() == JsonToken.STRING) {
// support strings for compatibility with GSON 1.7
return Boolean.parseBoolean(reader.nextString());
}
return reader.nextBoolean();
}

View File

@ -38,10 +38,10 @@ public class JsonPrimitiveTest extends TestCase {
// Extra support for booleans
json = new JsonPrimitive(1);
assertTrue(json.getAsBoolean());
assertFalse(json.getAsBoolean());
json = new JsonPrimitive("1");
assertTrue(json.getAsBoolean());
assertFalse(json.getAsBoolean());
json = new JsonPrimitive("true");
assertTrue(json.getAsBoolean());

View File

@ -21,10 +21,13 @@ import com.google.gson.GsonBuilder;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSyntaxException;
import com.google.gson.LongSerializationPolicy;
import com.google.gson.reflect.TypeToken;
import java.io.Serializable;
import java.io.StringReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
import junit.framework.TestCase;
/**
@ -792,4 +795,10 @@ public class PrimitiveTest extends TestCase {
gson.fromJson("12121211243123245845384534687435634558945453489543985435", BigDecimal.class);
assertEquals("12121211243123245845384534687435634558945453489543985435", actual.toPlainString());
}
public void testStringsAsBooleans() {
String json = "['true', 'false', 'TRUE', 'yes', '1']";
assertEquals(Arrays.asList(true, false, true, false, false),
gson.<List<Boolean>>fromJson(json, new TypeToken<List<Boolean>>() {}.getType()));
}
}