DonaldDu / google-gson

Automatically exported from code.google.com/p/google-gson
0 stars 0 forks source link

Enable Escape All Non Ascii chars #388

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Enable Escape All Non Ascii chars
like php json_encode

Original issue reported on code.google.com by farmer1...@gmail.com on 10 Dec 2011 at 5:22

Attachments:

GoogleCodeExporter commented 9 years ago
Eww, why would you do this? You're better off fixing your other tools that 
can't handle Unicode.

Original comment by limpbizkit on 10 Dec 2011 at 10:20

GoogleCodeExporter commented 9 years ago
this is important to cjk non-unicode users
e.g. 
the page encoded in gbk
and wanted to export json data
servlet will encode json using gbk if not escaped

make all non ascii would be safe for javascript to use

jackson1.8 and php json_encode always have this feature

Original comment by farmer1...@gmail.com on 11 Dec 2011 at 9:46

GoogleCodeExporter commented 9 years ago
Its about an hour's work to make a Writer subclass that does what you'd like. 
There's no benefit to doing this in Gson directly.

Original comment by limpbizkit on 11 Dec 2011 at 2:47

GoogleCodeExporter commented 9 years ago
... actually it was only about eight minutes work. Paste this class into your 
application (public domain license) and use it when you create your JsonWriter. 
There's some optimization opportunities if write() isn't fast enough; changes 
are it'll be fine.

public class GhettoAsciiWriter extends Writer {
    private final Writer out;

    public GhettoAsciiWriter(Writer out) {
        this.out = out;
    }

    @Override public void write(char[] buffer, int offset, int count) throws IOException {
        for (int i = 0; i < count; i++) {
            char c = buffer[i + offset];
            if (c <= 0x7f) {
                out.write(c);
            } else {
                out.write(String.format("\\u%04x", (int) c));
            }
        }
    }

    @Override public void flush() throws IOException {
        out.flush();
    }

    @Override public void close() throws IOException {
        out.close();
    }
}

Original comment by limpbizkit on 11 Dec 2011 at 10:39