Required adapter to convert long values
I have this GSON code used to parse JSON files:
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class LongTypeAdapter extends TypeAdapter {
private static final Logger logger = LoggerFactory.getLogger(LongTypeAdapter.class);
@Override
public Long read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
String stringValue = reader.nextString();
try {
if (!StringUtils.isEmpty(stringValue)) {
return (long) Double.parseDouble(stringValue);
}
} catch (NumberFormatException e) {
logger.error("Failed to convert string to long ", e);
}
logger.error("Failed to convert string to long {}", stringValue);
return null;
}
@Override
public void write(JsonWriter writer, Long value) throws IOException {
if (value == null) {
writer.nullValue();
return;
}
writer.value(value);
}
}
.....
private static final Gson gson = new GsonBuilder().registerTypeAdapter(Long.class, new LongTypeAdapter())
.registerTypeAdapter(Double.class, new DoubleTypeAdapter()).create();
I want to migrate this code to Jackson:
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class LongDeserializer extends StdDeserializer {
private static final Logger logger = LoggerFactory.getLogger(LongDeserializer.class);
public LongDeserializer() {
super(Long.class);
}
@Override
public Long deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
JsonToken token = p.currentToken();
if (token == JsonToken.VALUE_NULL) {
return null;
}
// Handle string values like "123.45"
if (token == JsonToken.VALUE_STRING) {
String text = p.getText().trim();
if (StringUtils.isEmpty(text)) {
return null;
}
try {
return (long) Double.parseDouble(text);
} catch (NumberFormatException e) {
logger.error("Failed to convert string to long: {}", text, e);
return null;
}
}
// Handle numeric tokens directly
if (token == JsonToken.VALUE_NUMBER_INT) {
return p.getLongValue();
}
if (token == JsonToken.VALUE_NUMBER_FLOAT) {
return (long) p.getDoubleValue();
}
// Unexpected token
logger.error("Unexpected token {} for Long value", token);
return null;
}
}
I'm not sure do I need this custom deserializer for Long values of Jackson will do this conversion automatically?