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) {
        if (str == null) {
            return str;
        }/*from w  w w  . j  a v a  2  s.  c o m*/
        StringBuilder sb = new StringBuilder();
        int len = str.length();
        for (int i = 0; i < len; i++) {
            char c = str.charAt(i);
            switch (c) {
            case '\"':
                sb.append("\\\"");
                break;
            case '\\':
                sb.append("\\\\");
                break;
            case '/':
                sb.append("\\/");
                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:
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public static String toString(Object object, String defaultvalue) {
        if (object == null) {
            return defaultvalue;
        }
        if (object instanceof String) {
            return (String) object;
        }
        return object.toString();
    }

    public static String toString(Object[] obj) {
        if (obj == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < obj.length; i++) {
            sb.append(obj[i]);
            if (i < obj.length - 1) {
                sb.append(",");
            }
        }
        return sb.toString();
    }
}

Related

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