1

I want to check for valid Integer's when deserializing with GSON and report errors to an resultList object.

So I have this (register the Integer type) to GsonBuilder:

gson.registerTypeAdapter(Integer.class, new IntegerDeserializer(resultList));

And the IntegerDeserializer looks like

@Override
public Integer deserialize(JsonElement element, Type arg1, JsonDeserializationContext context) throws JsonParseException {

    String integer = element.getAsString();

    try {
        Integer value = Integer.valueOf(integer);
        return value;
    } catch (NumberFormatException e) {
        resultList.addError("?? fieldname ?? ", "Invalid number");
        return null;
    }
}

Is there a way to get the field name of the current Integer that is parsed? If this works I can use this as a generic way for checking json fields.

Rey333
  • 350
  • 2
  • 12
  • Using a type adapter you can get the field name from the [`JsonReader`](https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html). See also this [question](http://stackoverflow.com/questions/8863429/how-to-handle-a-numberformatexception-with-gson-in-deserialization-a-json-respon?rq=1) –  Jun 14 '15 at 08:55
  • I looked at the link but can't find a way to reach the field name. I think that once you reach the TypeAdapter (i.e. Integer) you're too late..but maybe you can give an example? – Rey333 Jun 14 '15 at 09:24

0 Answers0