Java Json Escape escape4Json(String source)

Here you can find the source of escape4Json(String source)

Description

escape Json

License

Open Source License

Declaration

public static String escape4Json(String source) 

Method Source Code

//package com.java2s;

import java.text.CharacterIterator;

import java.text.StringCharacterIterator;

public class Main {
    static char[] hex = "0123456789ABCDEF".toCharArray();

    public static String escape4Json(String source) {
        if (source == null) {
            return "";
        }// w w w  . ja v a 2s.c  o m
        StringBuilder buf = new StringBuilder();
        CharacterIterator it = new StringCharacterIterator(source);
        for (char c = it.first(); c != CharacterIterator.DONE; c = it
                .next()) {
            if (c == '"') {
                buf.append("\\\"");
            } else if (c == '\\') {
                buf.append("\\\\");
            } else if (c == '/') {
                buf.append("\\/");
            } else if (c == '\b') {
                buf.append("\\b");
            } else if (c == '\f') {
                buf.append("\\f");
            } else if (c == '\n') {
                buf.append("\\n");
            } else if (c == '\r') {
                buf.append("\\r");
            } else if (c == '\t') {
                buf.append("\\t");
            } else if (Character.isISOControl(c)) {
                unicode(buf, c);
            } else {
                buf.append(c);
            }
        }
        return buf.toString();
    }

    /**
     * Represent as unicode
     * 
     * @param c
     *            character to be encoded
     */
    private static void unicode(StringBuilder buf, char c) {
        buf.append("\\u");
        int n = c;
        for (int i = 0; i < 4; ++i) {
            int digit = (n & 0xf000) >> 12;
            buf.append(hex[digit]);
            n <<= 4;
        }
    }
}

Related

  1. escapeJSON(String aText)
  2. jsonEscape(CharSequence s)
  3. jsonEscape(String in)
  4. jsonEscape(String s)