Java Json String Create toJson(String s)

Here you can find the source of toJson(String s)

Description

Converts a String to a JSON String.

License

Open Source License

Declaration

public static String toJson(String s) 

Method Source Code

//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;
        }
    }
}

Related

  1. toJson()
  2. toJson(final Document doc)
  3. toJson(Object value)
  4. toJson(String jsonp)
  5. toJson(String org)
  6. toJson(String str)
  7. toJson(String str)
  8. toJSON(String string)
  9. toJsonArrays(String... strings)