简体   繁体   中英

Jackson + YAML for Not A Number (.NAN)

Per the YAML spec, Not-a-number is represented as .NAN https://yaml.org/refcard.html

However, when deserialized with jackson-dataformats-text 's YAMLMapper , we get:

Malformed numeric value '.NAN'

How do you tell an ObjectMapper to accept a given string as a representing null without diving into custom deserializers? Or is there a YAML-specific feature I should be enabling?

If you use NULL , it works on the Jackson side, but then it's no longer valid YAML and schema-aware editors like VS Code know it, which is confusing to end users:

VS 代码无法验证 null

I've solved this by bypassing the YAMLMapper and going to SnakeYAML's Yaml directly. I did this to fix the issue of Jackson not resolving anchors, but then I realized it also solved the .NaN /null problem as well- .NaN s are now parsed correctly as Double.NaN

static final Yaml YAML = new Yaml();
static final ObjectMapper MAPPER = new ObjectMapper();
...

// Use SnakeYAML directly to resolve anchors and handle .NaN
protected static <T> T load(Path p, Class<T> cls) throws IOException {
    val yaml = YAML.load(Files.newInputStream(p));
    return MAPPER.treeToValue(MAPPER.valueToTree(yaml), cls);
}

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