Here you can find the source of toJson(String s)
public static String toJson(String s)
//package com.java2s; // Released under the Apache License, Version 2.0 public class Main { /**/*from ww w . j a v a2 s . c o m*/ * Converts a String to a JSON String. * Returns null if the String is null. */ public static String toJson(String s) { if (s != null) { StringBuilder sb = new StringBuilder(); sb.append('"'); int len = s.length(); for (int i = 0; i < len; i++) { char c = s.charAt(i); switch (c) { case '\\': case '"': case '/': sb.append('\\').append(c); 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; default: if (c < ' ' || c > '~') { // Replace any special chars with \u1234 unicode String hex = "000" + Integer.toHexString(c); hex = hex.substring(hex.length() - 4); sb.append("\\u" + hex); } else { sb.append(c); } break; } } sb.append('"'); return sb.toString(); } else { return null; } } }