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!
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
}
}
}`
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);
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
}
}
}`