Transform Java String to JSON string. - Java JSON

Java examples for JSON:JSON String

Description

Transform Java String to JSON string.

Demo Code

/*//from www  .  j a v  a 2 s .c o  m
 * Copyright (C) 2009 eXo Platform SAS.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
//package com.java2s;

public class Main {
    /**
     * Transform Java String to JSON string.
     *
     * @param string source String.
     * @return result.
     */
    public static String getJsonString(String string) {
        if (string == null || string.length() == 0)
            return "\"\"";
        StringBuffer sb = new StringBuffer();
        sb.append("\"");
        char[] charArray = string.toCharArray();
        for (char c : charArray) {
            switch (c) {
            case '\n':
                sb.append("\\n");
                break;
            case '\r':
                sb.append("\\r");
                break;
            case '\t':
                sb.append("\\t");
                break;
            case '\b':
                sb.append("\\b");
                break;
            case '\f':
                sb.append("\\f");
                break;
            case '\\':
                sb.append("\\\\");
                break;
            case '"':
                sb.append("\\\"");
                break;
            default:
                if (c < '\u0010')
                    sb.append("\\u000" + Integer.toHexString(c));
                else if ((c < '\u0020' && c > '\u0009')
                        || (c >= '\u0080' && c < '\u00a0'))
                    sb.append("\\u00" + Integer.toHexString(c));
                else if (c >= '\u2000' && c < '\u2100')
                    sb.append("\\u" + Integer.toHexString(c));
                else
                    sb.append(c);
                break;
            }
        }
        sb.append("\"");
        return sb.toString();
    }
}

Related Tutorials