escape JSON String - Java JSON

Java examples for JSON:JSON String

Description

escape JSON String

Demo Code


import java.io.File;
import java.io.IOException;
import org.apache.log4j.Logger;

public class Main{
    public static void main(String[] argv) throws Exception{
        String s = "java2s.com";
        System.out.println(escapeJSON(s));
    }/* ww  w. j  a  va 2 s . c o m*/
    public static final String escapeJSON(String s) {
        StringBuffer sb = new StringBuffer();
        int n = s.length();
        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            switch (c) {
            case '"':
                sb.append("\\\"");
                break;
            case '\'':
                sb.append("\\\'");
                break;

            default:
                sb.append(c);
            }
        }
        return sb.toString();
    }
}

Related Tutorials