1

Object convert JSON, Bigdecimal was wrong,not String

    public static void main(String[] args) {
        Obj obj = new Obj();
        obj.val = new BigDecimal("100");
        obj.name = "hello";
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNodes = mapper.convertValue(obj, JsonNode.class);
        System.out.println(jsonNodes);
    }
    class Obj implements Serializable {
    String name;

    BigDecimal val;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BigDecimal getVal() {
        return val;
    }

    public void setVal(BigDecimal val) {
        this.val = val;
    }
}

the result was

{"name":"hello","val":1E+2}

how can i do,let this become {"name":"hello","val":"100"}

A Paul
  • 8,113
  • 3
  • 31
  • 61
lhz1165
  • 67
  • 1
  • 8

1 Answers1

2

Although other users pointed to the existing answer, sometime using mapper = mapper.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true); does not work, which I have faced. I have used below. Use

mapper = mapper.setNodeFactory(JsonNodeFactory.withExactBigDecimals(true));

Like below

Obj obj = new Obj();
obj.val = new BigDecimal("100");
obj.name = "hello";
ObjectMapper mapper = new ObjectMapper();
mapper = mapper.setNodeFactory(JsonNodeFactory.withExactBigDecimals(true));
com.fasterxml.jackson.databind.JsonNode jsonNodes = mapper.convertValue(obj, com.fasterxml.jackson.databind.JsonNode.class);
System.out.println(jsonNodes);
A Paul
  • 8,113
  • 3
  • 31
  • 61