Answer the question
In order to leave comments, you need to log in
How to convert string to number in Jackson?
Hello, there is an object, but it just so happened that one field is already stored in different types, in String and Integer, {"s":"5.666"} а также {"s":5}
as well as the private Integer s = null;
actual error itself
com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.lang.Integer from String value '5.666': not a valid Integer value
Answer the question
In order to leave comments, you need to log in
You need to write your own JsonDeserializer and specify it in the @JsonDeserialize annotation above the field setter with which you have problems
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.io.IOException;
public class TestJackson {
Integer a;
public Integer getA() {
return a;
}
@JsonDeserialize(using = StringIntegerDeserializer.class)
public void setA(Integer a) {
this.a = a;
}
@Override
public String toString() {
return "TestJackson{a=" + a + "}";
}
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String json = "{\"a\":\"5.666\"}";
System.out.println(mapper.readValue(json, TestJackson.class));
json = "{\"a\":5.666}";
System.out.println(mapper.readValue(json, TestJackson.class));
json = "{\"a\":5}";
System.out.println(mapper.readValue(json, TestJackson.class));
}
public static class StringIntegerDeserializer extends JsonDeserializer<Integer> {
@Override
public Integer deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
String valueAsString = jsonParser.getValueAsString();
int integer = (int) Double.parseDouble(valueAsString);
return integer;
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question