Java Json Escape escapeJSON(String aText)

Here you can find the source of escapeJSON(String aText)

Description

escape JSON

License

Apache License

Declaration

public static String escapeJSON(String aText) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.text.StringCharacterIterator;

public class Main {
    public static String escapeJSON(String aText) {
        if (aText == null) {
            return null;
        }// w w  w  .  jav  a 2s  .  co m
        final StringBuilder result = new StringBuilder();
        StringCharacterIterator iterator = new StringCharacterIterator(aText);
        char character = iterator.current();
        while (character != StringCharacterIterator.DONE) {
            if (character == '\"') {
                result.append("\\\"");
            } else if (character == '\\') {
                result.append("\\\\");
            } else if (character == '/') {
                result.append("\\/");
            } else if (character == '\b') {
                result.append("\\b");
            } else if (character == '\f') {
                result.append("\\f");
            } else if (character == '\n') {
                result.append("\\n");
            } else if (character == '\r') {
                result.append("\\r");
            } else if (character == '\t') {
                result.append("\\t");
            } else {
                // the char is not a special one
                // add it to the result as is
                result.append(character);
            }
            character = iterator.next();
        }
        return result.toString();
    }
}

Related

  1. escape4Json(String source)
  2. jsonEscape(CharSequence s)
  3. jsonEscape(String in)
  4. jsonEscape(String s)
  5. JsonEscape(String str)