I'm making requests to a HTTP server sending JSON string. I used Gson for serializing and deserializing JSON objects. Today I observed this pretty weird behavior that I don't understand.
I have:
String jsonAsString = gson.toJson(jsonAsObject).replace("\"", "\\\"");
System.out.println(jsonAsString);
That outputs exactly this:
{\"content\":\"Literal\",\"pos\":{\"left\":20,\"top\":20}}
Now I'm using OutputStreamWriter obtained from HttpURLConnection to make HTTP, PUT request with JSON payload. The foregoing request works fine:
os.write("{\"content\":\"Literal\",\"pos\":{\"left\":20,\"top\":20}}");
However, when I say:
os.write(jsonAsString);
...the request doesn't work (this server doesn't return any errors but I can see that when writing JSON as string object it doesn't do what it should). Is there a difference when using string literal over string object. Am I doing something wrong?
Here is the snippet:
public static void EditWidget(SurfaceWidget sw, String widgetId) {
Gson gson = new Gson();
String jsonWidget = gson.toJson(sw).replace("\"", "\\\"");
System.out.println(jsonWidget);
try {
HttpURLConnection hurl = getConnectionObject("PUT", "http://fltspc.itu.dk/widget/5162b1a0f835c1585e00009e/");
hurl.connect();
OutputStreamWriter os = new OutputStreamWriter(hurl.getOutputStream());
//os.write("{\"content\":\"Literal\",\"pos\":{\"left\":20,\"top\":20}}");
os.write(jsonWidget);
os.flush();
os.close();
System.out.println(hurl.getResponseCode());
} catch (IOException e) {
e.printStackTrace();
}
}
解决方案
Remove the .replace("\"", "\\\"") instruction. It's unnecessary.
You're forced to add slashes before double quotes when you send a JSON String literal because in a Java String literal, double quotes must be escaped (otherwise, they would mark the end of the String instead of being a double quote inside the String).
But the actual String, in the bytecode, doesn't contain these backslashes. They're only used in the source code.