java outputstring,Java中OutputStreamWriter中的字符串对象与字符串文字

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值