1. 程式人生 > >java格式化json資料(如斜槓...)

java格式化json資料(如斜槓...)

public static String escapeJson(String string){
		if (string == null || string.length() == 0){
			return string;
		}
        char b,c = 0;
        int len = string.length();
        StringBuilder sb = new StringBuilder(len+4);
        String t;
      
        for (int i=0;i<len;i ++){
            b = c;
            c = string.charAt(i);
            switch (c){
	            case '\\':
	            	sb.append("\\\\");
	                break;
	            case '\'':
	                sb.append("\\'");
	                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 <' '||(c >='\u0080'&&c <'\u00a0')||(c >='\u2000'&& c <'\u2100')){
	                    t = "000" + Integer.toHexString(c);
	                    sb.append("\\u"+t.substring(t.length()-4));
	                }else{
	                	sb.append(c);
	                }
            }
        }
      
        System.out.println(sb.toString());
        try{return sb.toString();}finally{sb=null;}
	}