简体   繁体   English

最快的方法是从java中删除JSON中的注释?

[英]Fastest means of removing comments from JSON in java?

Looked all around the internet for a java port of a reliable json comment stripper and minifier, but most were flawed designs (not supporting multiline comments, or comment patterns within strings). 在互联网上查看可靠的json评论剥离器和缩小器的Java端口,但大多数都是有缺陷的设计(不支持多行注释,或字符串中的注释模式)。

So in my haste, I went and threw this together: https://gist.github.com/justisr/abab012af3ef399908798a687185d49a 所以在我的匆忙中,我把它扔到了一起: https//gist.github.com/justisr/abab012af3ef399908798a687185d49a

Gave it a test on an existing json file I had, and everything came out as expected, but I'm not satisfied. 对我现有的json文件进行了测试,所有内容都按预期发布,但我并不满意。 Is there really no faster/standard means of stripping comments from a json string? 是否真的没有更快/标准的方法从json字符串中删除注释?

Previously I was using https://github.com/getify/JSON.minify but it was slow and again, a regular // comment at the end of the file broke it, hence my desperation. 以前我使用的是https://github.com/getify/JSON.minify,但它很慢,而且文件末尾的常规//注释打破了它,因此我绝望了。

Simplest thing would be to run your JSON through Jackson : 最简单的方法是通过杰克逊运行你的JSON:

public static String removeComments(String json) throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  mapper.enable(JsonParser.Feature.ALLOW_COMMENTS);
  return mapper.writeValueAsString(mapper.readTree(json));
}

If you wanted to get fancier, you could use Jackson's streaming API to avoid buffering the document in memory, but unless your documents are large or performance is absolutely critical, that's probably overkill. 如果你想获得更好的,你可以使用Jackson的流媒体API来避免在内存中缓冲文档,但除非你的文档很大或性能绝对是关键的,否则这可能是过度的。

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

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