Suppose i want to override the boolean type - to add default value in
case empty string is introduced.
In my case the builtin adapter doesnt cope with empty string and i am
getting NumberFormatException: For input string: ""
test case:
public static void main(String[] args)
{
String json = "{\"rows\": [{\"id\":\"\",\"name\":\"New
Field1\",\"type\":\"String\",\"list_visible\":\"true\"},{\"id\":\"\",
\"name\":\"New Field2\",\"type\":\"Number\",\"list_visible\":\"\"}]}";
try
{
System.out.println(json);
GsonBuilder gb = new GsonBuilder();
// allow null values for long (id)
gb.registerTypeAdapter(Long.class, new
JsonDeserializer<Long>()
{
public Long deserialize(JsonElement jsonElement, Type
type, JsonDeserializationContext jsonDeserializationContext) throws
JsonParseException
{
System.out.println("ttt"); // Never printed !!!
String str =
jsonElement.getAsJsonPrimitive().getAsString();
if (str.length() == 0)
return null;
else
return Long.parseLong(str);
}
});
// allow default value of false
gb.registerTypeAdapter(Boolean.class, new
JsonDeserializer<Boolean>()
{
public Boolean deserialize(JsonElement jsonElement,
Type type, JsonDeserializationContext jsonDeserializationContext)
throws JsonParseException
{
String str =
jsonElement.getAsJsonPrimitive().getAsString();
if (str.length() == 0)
return false;
else
return Boolean.parseBoolean(str);
}
});
Gson g = gb.create();
FieldsGrid fieldsGrid = g.fromJson(json,
FieldsGrid.class);
}
catch (Exception e)
{
e.printStackTrace(); //To change body of catch statement
use File | Settings | File Templates.
}
}
private static class FieldsGridRowInstanceCreator implements
InstanceCreator<FieldsGridRowInstanceCreator>
{
public FieldsGridRowInstanceCreator createInstance(Type type)
{
return null; //To change body of implemented methods use
File | Settings | File Templates.
> r281
http://code.google.com/p/google-gson/source/detail?r=281
> This bug does indeed exist, and the culprit is navigateClassFields
> method of ObjectNavigator. That method does not invoke a custom type
> adapter for primitive types or strings. I reopened the bughttp://
code.google.com/p/google-gson/issues/detail?id=68