简体   繁体   English

Jackson + YAML 用于非数字 (.NAN)

[英]Jackson + YAML for Not A Number (.NAN)

Per the YAML spec, Not-a-number is represented as .NAN https://yaml.org/refcard.html根据 YAML 规范,非数字表示为.NAN https://yaml.org/refcard.html

However, when deserialized with jackson-dataformats-text 's YAMLMapper , we get:但是,当使用jackson-dataformats-text YAMLMapper jackson-dataformats-textYAMLMapper反序列YAMLMapper ,我们得到:

Malformed numeric value '.NAN'格式错误的数值“.NAN”

How do you tell an ObjectMapper to accept a given string as a representing null without diving into custom deserializers?你如何告诉ObjectMapper接受给定的字符串作为表示 null 而不深入到自定义反序列化器? Or is there a YAML-specific feature I should be enabling?或者我应该启用特定于 YAML 的功能吗?

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:如果你使用NULL ,它在 Jackson 端工作,但它不再是有效的 YAML 和模式感知编辑器,比如 VS Code 知道它,这会让最终用户感到困惑:

VS 代码无法验证 null

I've solved this by bypassing the YAMLMapper and going to SnakeYAML's Yaml directly.我通过绕过YAMLMapper并直接转到 SnakeYAML 的Yaml解决了这个问题。 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我这样做是为了解决 Jackson 没有解决锚点的问题,但后来我意识到它也解决了.NaN /null 问题 - .NaN现在被正确解析为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);
}

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

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