Here you can find the source of jsonEscape(String str)
public static String jsonEscape(String str)
//package com.java2s; /*/*from w ww . j a v a 2 s . c o m*/ * This file is part of Pustefix. * * Pustefix is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Pustefix is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Pustefix; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ public class Main { final static char[] ESC_CHARS = { 'b', 'f', 'n', 'r', 't', '\\', '"' }; final static char[] ESC_MAP = { '\b', '\f', '\n', '\r', '\t', '\\', '"' }; public static String jsonEscape(String str) { StringBuilder sb = new StringBuilder(); sb.append("\""); for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); int found = -1; for (int k = 0; k < ESC_MAP.length && found == -1; k++) { if (ch == ESC_MAP[k]) found = k; } if (found > -1) sb.append("\\" + ESC_CHARS[found]); else if (ch < '\u0020') { String hexStr = Integer.toHexString(ch); if (hexStr.length() == 1) hexStr = "0" + hexStr; sb.append("\\u00" + hexStr); } else sb.append(ch); } sb.append("\""); return sb.toString(); } }