Gson gson = new Gson();
JsonElement asTree = gson.toJsonTree(someObject);
StringWriter sw = new StringWriter();
JsonWriter jw = new MyJsonWriter(sw);
gson.toJson(asTree, jw);
sw.toString(); // your escaped string
public class MyJsonWriter extends JsonWriter {
private static Method JsonWriterWriteDeferredName;
private static Method JsonWriterBeforeValue;
static {
try {
JsonWriterWriteDeferredName =
JsonWriter.class.getDeclaredMethod("writeDeferredName");
JsonWriterWriteDeferredName.setAccessible(true);
JsonWriterBeforeValue =
JsonWriter.class.getDeclaredMethod("beforeValue", boolean.class);
JsonWriterBeforeValue.setAccessible(true);
} catch (Exception e) {
// This indicates a bug in the code above or a change in
one of the JsonWriter private methods
throw new RuntimeException(e);
}
}
private final Writer out;
public MyJsonWriter(Writer out) {
super(out);
this.out = out;
}
public JsonWriter value(String value) throws IOException {
if (value == null) {
return nullValue();
}
try {
try {
JsonWriterWriteDeferredName.invoke(this);
JsonWriterBeforeValue.invoke(this, false);
} catch (InvocationTargetException e) {
throw e.getCause();
}
} catch (IOException e) {
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
// This represents a bug in this code somewhere
throw new RuntimeException(e);
}
string(value);
return this;
}
/* This version escapes only double-quote. If you need to escape
more, refer to JsonWriter.string */
private void string(String value) throws IOException {
out.write("\"");
for (int i = 0; length = value.length(); i < length; i++) {
char c = value.charAt(i);
if (c == '"') { // That's ' " '
out.write("\\\""); // That's " \ \ \ \ " "
} else {
out.write(c);
}
}
}
}
> --
> You received this message because you are subscribed to the Google Groups
> "google-gson" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/google-gson/-/DpE_I9coXy0J.
> To post to this group, send email to googl...@googlegroups.com.
> To unsubscribe from this group, send email to
> google-gson...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/google-gson?hl=en.
On Mon, Mar 12, 2012 at 4:56 PM, Brandon Mintern <min...@easyesi.com> wrote:
...
> out.write("\\\""); // That's " \ \ \ \ " "
The comment should have read:
// That's " \ \ \ " "
It's an escaped backslash and an escaped quote.
--
You received this message because you are subscribed to the Google Groups "google-gson" group.