M
M
Mark Ivanych2016-02-29 00:22:44
Java
Mark Ivanych, 2016-02-29 00:22:44

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

Tell me how to process a string and format it in Integer

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evhen, 2016-02-29
@iormark

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;
    }
  }
}

M
MamOn, 2016-02-29
@MamOn

Integer is an integer type. If you need to store non-integer numbers, then use Double or BigDecimal in pojo.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question