set Jackson ObjectMapper class not to use scientific notation for double

前端 未结 2 1959
予麋鹿
予麋鹿 2020-12-10 14:25

I am using a library com.fasterxml.jackson library for JsonSchema, I am creating creating an IntegerSchema object, when I set range for integer schema using below code:

相关标签:
2条回答
  • 2020-12-10 14:56

    Feature.WRITE_BIGDECIMAL_AS_PLAIN set this for your Object Mapper

    0 讨论(0)
  • 2020-12-10 15:03

    this is a java issue somewhat I believe. If you debug your program, your Double will always be displayed scientifically, so what we'll want is to force it into a String. This can be achieved in Java in multiple ways, and you can look it up here:

    How to print double value without scientific notation using Java?

    In terms of your specific question about Jackson, I've written up some code for you:

    public class ObjectMapperTest {
    
        public static void main(String[] args) throws JsonProcessingException {
    
            IntegerSchema schema = new IntegerSchema();
            schema.type = "Int";
            schema.max = 10200000000d;
            schema.min = 100d;
    
            ObjectMapper m = new ObjectMapper();
    
            System.out.println(m.writeValueAsString(schema));
    
        }
    
        public static class IntegerSchema {
    
            @JsonProperty
            String type;
            @JsonProperty
            double min;
            @JsonProperty
            @JsonSerialize(using=MyDoubleDesirializer.class)
            double max;
        }
    
        public static class MyDoubleDesirializer extends JsonSerializer<Double> {
    
    
            @Override
            public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers)
                    throws IOException, JsonProcessingException {
                // TODO Auto-generated method stub
    
                BigDecimal d = new BigDecimal(value);
                gen.writeNumber(d.toPlainString());
            }
    
        }
    
    }
    

    The trick is to register a custom Serializer for your Double value. This way, you can control what you want.

    I am using the BigDecimal value to create a String representation of your Double. The output then becomes (for the specific example):

    {"type":"Int","min":100.0,"max":10200000000}
    

    I hope that solves your problem.

    Artur

    0 讨论(0)
提交回复
热议问题