Java Json Escape jsonEscape(String s)

Here you can find the source of jsonEscape(String s)

Description

json Escape

License

Apache License

Declaration

public static String jsonEscape(String s) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    public static String jsonEscape(String s) {
        StringBuilder sb = new StringBuilder();
        int len = s.length();
        for (int i = 0; i < len; i++) {
            char ch = s.charAt(i);
            switch (ch) {
            case '"':
                sb.append("\\\"");
                break;
            case '\\':
                sb.append("\\\\");
                break;
            case '\b':
                sb.append("\\b");
                break;
            case '\f':
                sb.append("\\f");
                break;
            case '\n':
                sb.append("\\n");
                break;
            case '\r':
                sb.append("\\r");
                break;
            case '\t':
                sb.append("\\t");
                break;
            case '/':
                sb.append("\\/");
                break;
            default:
                //Reference: http://www.unicode.org/versions/Unicode5.1.0/
                if ((ch >= '\u0000' && ch <= '\u001F') || (ch >= '\u007F' && ch <= '\u009F')
                        || (ch >= '\u2000' && ch <= '\u20FF')) {
                    String ss = Integer.toHexString(ch);
                    sb.append("\\u");
                    for (int k = 0; k < 4 - ss.length(); k++) {
                        sb.append('0');
                    }//from   ww  w . j a  va  2  s.  c o  m
                    sb.append(ss.toUpperCase());
                } else {
                    sb.append(ch);
                }
            }
        }
        return sb.toString();
    }
}

Related

  1. escape4Json(String source)
  2. escapeJSON(String aText)
  3. jsonEscape(CharSequence s)
  4. jsonEscape(String in)
  5. JsonEscape(String str)
  6. jsonEscape(String str)
  7. jsonEscape(String string)
  8. jsonEscapes(String str)