code: public static String jsonEncode(final String val) {
      if ((val == null) || (val.length() == 0)) {
        return "\"\"";
      }
  
      StringBuilder sb = new StringBuilder();
  
      /* \n    newline
       * \t   tab
       * \b   backspace
       * \f   form feed
       * \r   return
       * \"   "   (double quote)
       * \\   \    (back slash)
       */
  
      sb.append('"');
  
      for (int i = 0; i < val.length(); i++) {
        char ch = val.charAt(i);
  
        switch (ch) {
        case '\n':
          sb.append("\\n");
          break;
  
        case '\t':
          sb.append("\\t");
          break;
  
        case '\b':
          sb.append("\\b");
          break;
  
        case '\f':
          sb.append("\\f");
          break;
  
        case '\r':
          sb.append("\\r");
          break;
  
        case '"':
        case '/':
        case '\\':
          sb.append('\\');
          sb.append(ch);
          break;
  
        case ' ':
          sb.append(" ");
          break;
  
        default:
          if (Character.isISOControl(ch)) {
            String str = Integer.toHexString(ch);
            sb.append("\\u");
            sb.append("0000".substring(str.length() - 4));
            sb.append(str);
          } else {
            sb.append(ch);
          }
        }
      }
  
      sb.append('"');
      return sb.toString();
    }
docs: Encode a json string according to the statement:
  <p>In JSON only the backslash, double quote and ASCII control characters
  need to be escaped. Forward slashes may be escaped
  
  <p>I assume we also need to do the whitespace characters
  
  @param val
  @return encoded String