julman99 / gson-fire

A java library that adds some very useful features to Gson, like Date serializing to unix timestamp or RFC3339, method (getters) serialization, pre/post processors and many others. Check out the documentation to learn how to use it!
http://gsonfire.io
Other
226 stars 36 forks source link

Adding custom deserializer for Long throws an IllegalArgumentException when tryinh to convert a POJO to string #61

Open hdagan opened 3 months ago

hdagan commented 3 months ago

When running this simple example you will get the error in the image below. Please notice that if I replace in the pom file the depenency from gson-fire 1.9.0 to gson 2.11.0 this error doesn't happened

public static void main(String[] args) { SamplePojo samplePojo = new SamplePojo(); samplePojo.setX(10); samplePojo.setY(20); samplePojo.setZ(30); Gson gson = new GsonBuilder() .registerTypeAdapter(Long.class, new LongDeserializer()) .create(); String json = gson.toJson(samplePojo); System.out.println(json);

}

private static class SamplePojo {
    private long x;
    @JsonAdapter(LongDeserializer.class)
    private long y;

    private long z;

    public void setX(long x) {
        this.x = x;
    }

    public void setY(long y) {
        this.y = y;
    }

    public void setZ(long z) {
        this.z = z;
    }
}

The LongDeserializer is the simplest one I could think of `mport com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException;

import java.lang.reflect.Type;

public class LongDeserializer implements JsonDeserializer { @Override public Long deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { return json.getAsLong(); } catch (NumberFormatException e) { return null; // or handle it in some other way } } }`

image