Escape string to Json String - Android File Input Output

Android examples for File Input Output:Json String

Description

Escape string to Json String

Demo Code


//package com.java2s;

public class Main {

    static String string2Json(final String s) {
        final StringBuilder sb = new StringBuilder(s.length() + 20);
        sb.append('\"');
        for (int i = 0; i < s.length(); i++) {
            final char c = s.charAt(i);
            switch (c) {
            case '\"':
                sb.append("\\\"");
                break;
            case '\\':
                sb.append("\\\\");
                break;
            case '/':
                sb.append("\\/");
                break;
            case '\b':
                sb.append("\\b");
                break;
            case '\f':
                sb.append("\\f");
                break;
            case '\n':
                sb.append("\\n");
                break;
            case '\r':
                sb.append("\\r");
                break;
            case '\t':
                sb.append("\\t");
                break;
            default:
                sb.append(c);//w  w  w.  j a  v  a2  s . c o  m
            }
        }
        sb.append('\"');
        return sb.toString();
    }
}

Related Tutorials