1 回答
TA贡献1804条经验 获得超2个赞
为简单起见,假设您的JSON有效负载是:
{
"timestamp": 1555323142345.345
}
它应该适合:
class Pojo {
private long timestamp;
// getters, setters, toString
}
解决方案取决于您是否可以更改Pojo模型。如果是并且您想要存储double并且long可以将类型更改为Number:
private Number timestamp;
你应该能够解析double' 和long' 的时间戳。如果您总是想要long实现自定义反序列化器:
class LongOrDoubleJsonDeserializer implements JsonDeserializer<Long> {
@Override
public Long deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (json.isJsonPrimitive()) {
Number number = json.getAsNumber();
return number.longValue();
}
return null;
}
}
您的Pojo财产应如下所示:
@JsonAdapter(LongOrDoubleJsonDeserializer.class)
private long timestamp;
如果您无法更改Pojo课程,则需要TypeAdapterFactory使用自定义和注册GsonBuilder。请参阅此链接:创建改造实例。自定义实现可能如下所示:
class LongOrDoubleTypeAdapterFactory implements TypeAdapterFactory {
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
Class<? super T> rawType = type.getRawType();
if (rawType == Long.class || rawType == long.class) {
return new TypeAdapter<T>() {
@Override
public void write(JsonWriter out, T value) {
}
@Override
public T read(JsonReader in) throws IOException {
try {
return (T) new Long(in.nextLong());
} catch (NumberFormatException e) {
return (T) new Long(((Double) in.nextDouble()).longValue());
}
}
};
}
return null;
}
}
并注册如下:
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(new LongOrDoubleTypeAdapterFactory())
.create();
添加回答
举报