JSON压缩:JSONMinify

JSON压缩:JSONMinify

JSONMinify  2014-04-01 17:23:16 发布
您的评价:
         
3.5 
     0收藏

JSONMinify 移除了 JSON 或者 JSON+C(JSON+C = JSON with comments) 文档中的所有空白和注释,实现对 JSON 内容的最小化压缩。实现无开销和近乎完美的表现。这个包只有53行源码:

public class JSONMinify {
  public static String minify(String jsonString) {
    boolean in_string = false;
    boolean in_multiline_comment = false;
    boolean in_singleline_comment = false;
    char string_opener = 'x'; // unused value, just something that makes compiler happy

    StringBuilder out = new StringBuilder();
    for (int i = 0; i < jsonString.length(); i++) {
      // get next (c) and next-next character (cc)

      char c = jsonString.charAt(i);
      String cc = jsonString.substring(i, Math.min(i+2, jsonString.length()));

      // big switch is by what mode we're in (in_string etc.)
      if (in_string) {
        if (c == string_opener) {
          in_string = false;
          out.append(c);
        } else if (c == '\\') { // no special treatment needed for \\u, it just works like this too
          out.append(cc);
          ++i;
        } else
          out.append(c);
      } else if (in_singleline_comment) {
        if (c == '\r' || c == '\n')
          in_singleline_comment = false;
      } else if (in_multiline_comment) {
        if (cc.equals("*/")) {
          in_multiline_comment = false;
          ++i;
        }
      } else {
        // we're outside of the special modes, so look for mode openers (comment start, string start)
        if (cc.equals("/*")) {
          in_multiline_comment = true;
          ++i;
        } else if (cc.equals("//")) {
          in_singleline_comment = true;
          ++i;
        } else if (c == '"' || c == '\'') {
          in_string = true;
          string_opener = c;
          out.append(c);
        } else if (!Character.isWhitespace(c))
          out.append(c);
      }
    }
    return out.toString();
  }
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值