简体   繁体   中英

Convert NaN value into null when parsing json using jackson library

What is the best way to parse a json string in to a JsonNode object, and convert all the NaN value in to null? The following code will convert the Nan to DoubleNode NaN. I try to register a custom deserializer but it didn't pick up the Nan node.

JsonMapper mapper =  JsonMapper.builder()
            .enable(JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS).build();

final String testJson =  "{\"key\":NaN}";
JsonNode node = mapper.readTree(testJson)

One way it could be done is like below

  1. Create some POJO class with @JsonSetter on setter method.
    public class KeyPojo {
    
        private Double key;
    
        @JsonSetter
        public void setKey(Double key) {
            if (Double.isNaN(key)) {
                this.key = null;
            } else {
                this.key = key;
            }
        }
    }
  1. And parse json text like below.

    KeyPojo keyObj = mapper.readValue(testJson, KeyPojo.class);

now, keyObj.key contains NULL value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM