Java Json String Create toJson(String str)

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

Description

to Json

License

Open Source License

Declaration

public static String toJson(String str) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static String toJson(String str) {
        int len = str.length();
        StringBuilder buf = new StringBuilder();
        buf.append('\"');
        for (int i = 0; i < len; i++) {
            char ch = str.charAt(i);
            if (ch == '\n')
                buf.append("\\n");
            else if (ch == '\r')
                buf.append("\\r");
            else if (ch == '\t')
                buf.append("\\t");
            else if (ch == '\b')
                buf.append("\\b");
            else if (ch < ' ' || ch >= 127) {
                String hex = Integer.toHexString((int) ch);
                int slen = hex.length();
                if (slen == 1)
                    hex = "000" + hex;
                else if (slen == 2)
                    hex = "00" + hex;
                else if (slen == 3)
                    hex = "0" + hex;
                buf.append("\\u");
                buf.append(hex);/*  w w  w  . ja v a  2s.co  m*/
            } else {
                if (ch == '\"' || ch == '\\')
                    buf.append('\\');
                buf.append(ch);
            }
        }
        buf.append('\"');
        return buf.toString();
    }
}

Related

  1. toJson(Object value)
  2. toJson(String jsonp)
  3. toJson(String org)
  4. toJson(String s)
  5. toJson(String str)
  6. toJSON(String string)
  7. toJsonArrays(String... strings)
  8. toJsonField(String name, String value)
  9. toJsonName(String name, int prefixLen)