Fastest means of removing comments from JSON in java?

justis :

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).

So in my haste, I went and threw this together: 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. Is there really no faster/standard means of stripping comments from a json string?

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.

dnault :

Simplest thing would be to run your JSON through Jackson:

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=73684&siteId=1