【问题标题】:String object vs. string literal in OutputStreamWriter in JavaJava 中 OutputStreamWriter 中的字符串对象与字符串文字
【发布时间】:2013-04-08 14:53:55
【问题描述】:

我正在向发送 JSON 字符串的 HTTP 服务器发出请求。我使用 Gson 序列化和反序列化 JSON 对象。今天我观察到这种非常奇怪的行为,我不明白。

我有:

String jsonAsString = gson.toJson(jsonAsObject).replace("\"", "\\\"");
System.out.println(jsonAsString);

输出就是这样:

{\"content\":\"Literal\",\"pos\":{\"left\":20,\"top\":20}}

现在我使用从HttpURLConnection 获得的OutputStreamWriter 来发出带有JSON 有效负载的HTTP、PUT 请求。上述请求工作正常:

os.write("{\"content\":\"Literal\",\"pos\":{\"left\":20,\"top\":20}}");

但是,当我说:

os.write(jsonAsString);

...请求不起作用(此服务器不返回任何错误,但我可以看到,当将 JSON 编写为字符串对象时,它没有做它应该做的事情)。在字符串对象上使用字符串文字时是否有区别。我做错了吗?

这里是sn-p:

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

【问题讨论】:

    标签: java json httpurlconnection


    【解决方案1】:

    删除.replace("\"", "\\\"") 指令。这是不必要的。

    当您发送 JSON 字符串 literal 时,您必须在双引号前添加斜杠,因为在 Java 字符串 literal 中,必须转义双引号(否则,它们将标记字符串的结尾,而不是字符串内的双引号)。

    但字节码中的实际字符串不包含这些反斜杠。它们只在源代码中使用。

    【讨论】:

      猜你喜欢
      • 2013-06-20
      • 2015-07-26
      • 2017-12-15
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多