Jackson YAML: support for tags

落花浮王杯 提交于 2021-01-27 19:29:23

问题


I'm investigating the use of YAML for a somewhat complicated metadata language. One thing that would be of great use is if the YAML parser supported the use of YAML tags. This would allow people who write documents in this metadata language to indicate when/if they are defining some object with a well-defined schema. For example:

set_one: !dset
  bass: tama rockstar 22x16
  snare: ludwig supralight 6.5x15
  tom1: tama rockstar 12x11
  tom2: tama rockstar 16x16

The use of the "!dset" tag in the above YAML is an indication, by the author, that the object defined by "set_one" is supposed to define a drumset and should be parsed according to the schema corresponding to "dset". If the object violates one of the constraints of that schema (for example, it does not define a hi-hat) the user would like to see the error at parsing time and not have it result in some, more opaque, runtime error.

I'm parsing the above sample like so:

  ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
  FileInputStream fis = null;

  try
  {
      fis = new FileInputStream(file);
      JsonNode nodeTree = mapper.readTree(fis);
      examineObject(nodeTree, 0);
  }
  ...

When I look at the JsonNode for "set_one" in the debugger, I don't see any trace of the "!dset" tag. I can think of a lot of cool things Jackson could do (e.g. use annotations to associate a Java class with a given tag and automatically deserialize the elements into an instance of that class) but, at a minimum, I need some way of discovering that that node was tagged with "dset". Does anyone know if/how I can do this?


回答1:


A JsonNode cannot contain any reference to a YAML tag because there is no such structure in JSON.

Be aware that Jackson is a high-level abstraction over JSON, XML, YAML and the like. What you want to do is YAML-specific - neither JSON nor XML have a direct equivalent of YAML's tag system (XML also has tags, but they are something entirely different). Therefore, Jackson is the wrong API to use this advanced YAML feature.

YAML support in Jackson is provided by SnakeYAML, which is perfectly able to deal with tags. So you probably want to use SnakeYAML's API instead of Jackson. Here is an example which, amongst other things, registers and uses a custom tag. Oh, and it is also able to use annotations to associate a Java class with a given tag and automatically deserialize the elements into an instance of that class.



来源:https://stackoverflow.com/questions/40095924/jackson-yaml-support-for-tags

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!