问题描述
我正在向发送JSON字符串的HTTP服务器发出请求.我使用Gson对JSON对象进行序列化和反序列化.今天,我观察到了这种我不理解的怪异行为.
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.
我有:
String jsonAsString = gson.toJson(jsonAsObject).replace("\"", "\\\"");
System.out.println(jsonAsString);
确切地输出以下内容:
{\"content\":\"Literal\",\"pos\":{\"left\":20,\"top\":20}}
现在我正在使用从HttpURLConnection
获得的OutputStreamWriter
来发出带有JSON有效负载的HTTP,PUT请求.前述要求运作良好:
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}}");
但是,当我说:
os.write(jsonAsString);
...请求无效(此服务器未返回任何错误,但我可以看到在将JSON作为字符串对象写入时,它没有执行应有的操作).在字符串对象上使用字符串文字时,有什么区别.我在做错什么吗?
...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?
以下是代码段:
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();
}
}
推荐答案
删除.replace("\"", "\\\"")
指令.没必要
在发送JSON字符串 literal 时,您被迫在双引号之前添加斜杠,因为在Java String literal 中,必须对双引号进行转义(否则,它们会被转义).会标记字符串的结尾,而不是在字符串内用双引号引起来.)
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).
但是字节码中的实际String不包含这些反斜杠.它们仅在源代码中使用.
But the actual String, in the bytecode, doesn't contain these backslashes. They're only used in the source code.
这篇关于Java中OutputStreamWriter中的字符串对象与字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!