JSON5: Provide a way to read/write a comment using `JsonNode`
I'd like to parse JSON5 containing comments. JsonReadFeature#ALLOW_JAVA_COMMENTS ignores comments when deserializing a JSON into a JsonNode.
https://github.com/FasterXML/jackson-core/blob/0fbb52961c5092d7d1f8e8f620b719f9eff48fcd/src/main/java/com/fasterxml/jackson/core/json/ReaderBasedJsonParser.java#L2521-L2523
As a result, we lose the comment information and cannot read/recover the original content from the parsed JsonNode.
A commentable JsonNode is useful so as to retrieve the original comment and serialize the JsonNode to JSON5 format.
Ok. So, it might be possible to write some comments through JsonNode by using "raw value" (and at streaming level, JsonGenerator.writeRaw() (NOT "rawValue" actually)) but that is definitely cumbersome.
But the real issue, and the reason why I am not sure we can ever fully support comments same way as regular tokens is that they can appear at any point in content and can not really be modeled well as nodes.
One thing that might be doable on reading side would be to allow registration of a callback to call when comment is encountered. This alone would only work at lowest level and require caller to handle difference between tokens read, comments, and somehow retain comment information. Further, any stylistic knowledge (white-space surrounding comment) would be lost.
So... while I can understand the need for exposing comments, I have never figured out a way they could be nicely handled at API level. In XML things are bit easier than JSON, in this case.
First of all, thank you for your interest in this issue. 🙇♂️
I am not sure we can ever fully support comments same way as regular tokens is that they can appear at any point in content and can not really be modeled well as nodes.
Agreed. It should be difficult to fully support comments. I speculated that some limited comments could be retained in positions right above nodes as a known limitation.
{
// A single line note for a node
foo: "bar",
/**
* Multiline note for a node
* could be supported.
*/
hello: "world"
}
I have never figured out a way they could be nicely handled at API level.
I'm not so sure that the following API style is possible but I just imagined:
interface CommentableNode {
String comment();
}
public class CommentableArrayNode extends ArrayNode implements CommentableNode {
...
}
JsonNode node = ...;
if (node instanceof CommentableNode) {
// do something with the comment
}
Unfortunately I don't thing add-on interfaces help a lot with the core issue (or maybe I just don't see it).
Support would still need to be added in JsonNode implementations.
But I guess there are multiple types of challenges in modeling here, both from containing and exposing information in general, and then api design etc.