Java String to JSON string


// the return value is already in double quotes
static String toJSONString(final String string) {

    if (string == null) {
        return "null";
    }

    final StringBuffer buffer = new StringBuffer();

    buffer.append("\"");

    final int length = string.length();
    for (int i = 0; i < length;) {
        final int codePoint = string.codePointAt(i);
        final char[] chars = Character.toChars(codePoint);
        for (int j = 0; j < chars.length; j++) {
            buffer.append("\\u");
            final int high = chars[j] >> 8;
            if (high <= 0x0F) {
                buffer.append('0');
            }
            buffer.append(Integer.toHexString(high).toUpperCase());
            final int low = chars[j] & 0xFF;
            if (low <= 0x0F) {
                buffer.append('0');
            }
            buffer.append(Integer.toHexString(low).toUpperCase());
        }
        i += chars.length;
    }

    buffer.append("\"");

    return buffer.toString();
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s