Escapes all characters in a string per JSON specification - Java JSON

Java examples for JSON:JSON String

Description

Escapes all characters in a string per JSON specification

Demo Code


import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Main{
    private static final int CONTROL_CHARACTER_RANGE = 0x80;
    private static final String[] CONTROL_CHARACTERS;
    /**//from   www .  jav a2  s.  c o  m
     * Escapes all characters in a string per JSON specification
     * @param input the string to escape
     * @return the input with all characters JSON escaped
     */
    private static String escapeJSON(String input) {
        StringBuilder builder = new StringBuilder();
        builder.append("\"");
        for (int i = 0; i < input.length(); i++) {
            char charIndex = input.charAt(i);
            if (charIndex < CONTROL_CHARACTER_RANGE) {
                String replacement = CONTROL_CHARACTERS[charIndex];
                if (replacement == null) {
                    builder.append(charIndex);
                } else {
                    builder.append(replacement);
                }
            } else if (charIndex == '\u2028') {
                // JavaScript interprets '\u2028' as newline
                builder.append("\\u2028");
            } else if (charIndex == '\u2029') {
                // JavaScript interprets '\u2029' as newline
                builder.append("\\u2029");
            } else {
                builder.append(charIndex);
            }
        }

        builder.append("\"");
        return builder.toString();
    }
}

Related Tutorials