简体   繁体   English

使用 jackson 库解析 json 时将 NaN 值转换为 null

[英]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?将 json 字符串解析为 JsonNode object 并将所有 NaN 值转换为 null 的最佳方法是什么? The following code will convert the Nan to DoubleNode NaN.以下代码会将 Nan 转换为 DoubleNode NaN。 I try to register a custom deserializer but it didn't pick up the Nan node.我尝试注册一个自定义反序列化器,但它没有选择 Nan 节点。

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.在 setter 方法上使用@JsonSetter创建一些 POJO class。
    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.并解析 json 文本,如下所示。

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

now, keyObj.key contains NULL value.现在,keyObj.key 包含 NULL 值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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