String object vs. string literal in OutputStreamWriter in Java

三世轮回 提交于 2019-12-12 03:47:22

问题


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();
        }
    }

回答1:


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.



来源:https://stackoverflow.com/questions/15882331/string-object-vs-string-literal-in-outputstreamwriter-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!