Java examples for JSON:JSON String
escape JSON String
import java.io.File; import java.io.IOException; import org.apache.log4j.Logger; public class Main{ public static void main(String[] argv) throws Exception{ String s = "java2s.com"; System.out.println(escapeJSON(s)); }/* ww w. j a va 2 s . c o m*/ public static final String escapeJSON(String s) { StringBuffer sb = new StringBuffer(); int n = s.length(); for (int i = 0; i < n; i++) { char c = s.charAt(i); switch (c) { case '"': sb.append("\\\""); break; case '\'': sb.append("\\\'"); break; default: sb.append(c); } } return sb.toString(); } }