Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable Escape All Non Ascii chars #388

Closed
GoogleCodeExporter opened this issue Mar 19, 2015 · 4 comments · May be fixed by #1984
Closed

Enable Escape All Non Ascii chars #388

GoogleCodeExporter opened this issue Mar 19, 2015 · 4 comments · May be fixed by #1984

Comments

@GoogleCodeExporter
Copy link

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
Copy link
Author

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

  • Changed state: WontFix

@GoogleCodeExporter
Copy link
Author

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
Copy link
Author

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
Copy link
Author

... 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant