mani-terrazas / google-gson

Automatically exported from code.google.com/p/google-gson
0 stars 0 forks source link

JsonReader#nextBoolean cannot consume quoted boolean values like nextDouble/Int/Long #579

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
JsonReader#nextDouble, nextInt, and nextLong all consume quoted values (e.g., 
both {x: 4} and {x: "4"} can be parsed).

But nextBoolean will throw an IllegalStateException: Expected a boolean but was 
STRING at ...

Is there a reason for this? Would it violate a spec to handle quoted "true" and 
"false" values in the nextBoolean method?

Original issue reported on code.google.com by o...@fleaflicker.com on 20 May 2014 at 9:43

GoogleCodeExporter commented 9 years ago
The quoted numbers are supported to defend against precision loss. In 
particular, for double-precision floating point values in JavaScript. There's 
no equivalent problem with booleans.

Original comment by limpbizkit on 9 Aug 2014 at 10:30

GoogleCodeExporter commented 9 years ago
Additionally, you can do this with a custom TypeAdapter.

public final class BooleanAdapter extends TypeAdapter<Boolean> {
    @Override
    public void write(JsonWriter out, Boolean value) throws IOException {
        if (value != null) {
            out.value(value);
        } else {
            out.nullValue();
        }
    }

    @Override
    public Boolean read(JsonReader in) throws IOException {
        JsonToken peek = in.peek();
        switch (peek) {
            case BOOLEAN:
                return in.nextBoolean();
            case STRING:
                return Boolean.parseBoolean(in.nextString());
            case NULL:
                in.nextNull();
                return null;
            default:
                throw new IllegalStateException("Expected BOOLEAN or STRING but was " + peek);
        }
    }

}

Original comment by j...@squareup.com on 10 Aug 2014 at 1:42