rithyskun / google-gson

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

JsonParseException when encountering an empty value for an int or long #472

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1. Create a data class with an int data member and a default value of 0 (any 
value would do).  Example:
public class GsonData {
    public int intValue = 0;
}

2. Create a json document with an empty value for intValue.  Example:
{
    "intValue":""
}
3. Parse the document:
String jsonString = < the json file as a string >
GsonData testDoc = new Gson().fromJson(jsonString, GsonData.class);

What is the expected output? 
I would expect that the document would parse correctly and result in intValue 
having the default value of 0.

What do you see instead?
It throws a parse exception because the empty value could not be converted to 
an int.

com.google.gson.JsonParseException: The JsonDeserializer IntegerTypeAdapter 
failed to deserialized json object "" given the type int

What version of the product are you using? 
gson-1.5.jar

On what operating system?
Windows 2008 R2

Please provide any additional information below.

Original issue reported on code.google.com by bryan.am...@gmail.com on 17 Sep 2012 at 4:00

GoogleCodeExporter commented 9 years ago
This solution posted here worked for me: 
https://groups.google.com/forum/#!msg/google-gson/kNf5HADtY14/bdD1xmDPbH0J

I created a new class as follows:

public class IntTypeAdapter extends TypeAdapter<Number> {

    @Override
    public void write(JsonWriter out, Number value)
            throws IOException {
        out.value(value);
    }

    @Override
    public Number read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        }
        try {
            String result = in.nextString();
            if ("".equals(result)) {
                return null;
            }
            return Integer.parseInt(result);
        } catch (NumberFormatException e) {
            throw new JsonSyntaxException(e);
        }
    }
}

And then ran the gson parsing as follows:

Gson gson = new GsonBuilder()
    .registerTypeAdapter(int.class, new IntTypeAdapter())
    .registerTypeAdapter(Integer.class, new IntTypeAdapter()).create();
myObject = gson.fromJson(myJsonString, Student.class);

Original comment by graili...@gmail.com on 25 Sep 2012 at 7:08

GoogleCodeExporter commented 9 years ago
Working as intended.

Original comment by limpbizkit on 4 Feb 2013 at 4:09