Java Json Escape jsonEscape(String string)

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

Description

json Escape

License

Apache License

Declaration

public static String jsonEscape(String string) 

Method Source Code

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

public class Main {
    public static String jsonEscape(String string) {
        if (string == null || string.length() == 0) {
            return "\"\"";
        }//from  w  w  w  .  ja  v a 2s.co m

        char c = 0;
        int i;
        int len = string.length();
        StringBuilder sb = new StringBuilder(len + 4);
        String t;

        for (i = 0; i < len; i += 1) {
            c = string.charAt(i);
            switch (c) {
            case '\\':
            case '"':
                sb.append('\\');
                sb.append(c);
                break;
            case '/':
                //                if (b == '<') {
                sb.append('\\');
                //                }
                sb.append(c);
                break;
            case '\b':
                sb.append("\\b");
                break;
            case '\t':
                sb.append("\\t");
                break;
            case '\n':
                sb.append("\\n");
                break;
            case '\f':
                sb.append("\\f");
                break;
            case '\r':
                sb.append("\\r");
                break;
            default:
                if (c < ' ') {
                    t = "000" + Integer.toHexString(c);
                    sb.append("\\u" + t.substring(t.length() - 4));
                } else {
                    sb.append(c);
                }
            }
        }
        return sb.toString();
    }
}

Related

  1. jsonEscape(CharSequence s)
  2. jsonEscape(String in)
  3. jsonEscape(String s)
  4. JsonEscape(String str)
  5. jsonEscape(String str)
  6. jsonEscapes(String str)