Gson 2.2.2 Json custom JsonWriter for JsonElement to avoid string escaping?

I have a use case in which I have a previously saved string returned as a JsonElement. However, JsonElement, internally using JsonWriter, will parse the string to try to perform a character / character replacement.

See https://code.google.com/p/google-gson/source/browse/trunk/gson/src/main/java/com/google/gson/stream/JsonWriter.java

private void string () method

I would like to avoid this for performance reasons, since my String element has been pre-escaped.

I did a search and found that this use case is similar: https://code.google.com/p/google-gson/issues/detail?id=239

Although the solution in the link above will work with gson1.5, the Escaper class was removed in the latest gson (2.2.2).

How can I extend a JsonElement (or an internal JsonWriter for it) so that I can avoid the overhead of replacing a JsonWriter string for a specific type?

+4
source share
1 answer

This seems to work.

OutputStream rawStream = ... JsonWriter writer = new JsonWriter(new OutputStreamWriter(rawStream, "UTF-8")); ... /* normal gson/json usage */ // about to write object including a base 64 big byte[] /* don't using binding API for images, too big, too slow */ String b64 = Base64.encodeToString(blob, Base64.NO_WRAP); writer.beginObject(); writer.flush(); /* gson.JsonWriter doesn't understand the string is b64 encoded, and hence doesn't need escaping, so lets use an ASCII encoder for a little while */ OutputStreamWriter asciiWriter = new OutputStreamWriter(rawStream, "ASCII"); asciiWriter.write( String.format("\"id\": \"%d\", \"raw\": \"", param.id) ); asciiWriter.write(b64); asciiWriter.write("\" "); asciiWriter.flush(); writer.endObject(); 

While not "in the API", this should continue to work, given that

  • The beginning of the JSON object is a known point (for example, there is no "state" to save after {)
  • the completion of an empty JSON object is also a known point ("you can just put a bracket")
  • Which, in turn, means that to write a valid JSON as ascii on average, you do not need to affect the state of the JSON record.

Note. I tested this, it works much faster than using JsonWriter.value (String value).

0
source

All Articles