Java JSONObject 包含转义字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19609205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:45:06  来源:igfitidea点击:

JSONObject contains escape characters

javajsonobject

提问by Christophe De Troyer

I'm building a simulator to post JSON data to a service I'm running.

我正在构建一个模拟器来将 JSON 数据发布到我正在运行的服务。

The JSON should look like this:

JSON 应如下所示:

{"sensor":
       {"id":"SENSOR1","name":"SENSOR","type":"Temperature","value":100.12,"lastDateValue":"\/Date(1382459367723)\/"}
}

I tried this with the "Advanced REST Client" in Chrome and this works fine. The date get's parsed properly by the ServiceStack webservice.

我在 Chrome 中使用“高级 REST 客户端”进行了尝试,效果很好。ServiceStack 网络服务正确解析了日期获取。

So, the point is to write a sensor simulator that posts data like this to the web service.

因此,关键是编写一个传感器模拟器,将这样的数据发布到 Web 服务。

I created this in Java, so I could run it on my raspberry pi.

我用 Java 创建了它,所以我可以在我的树莓派上运行它。

This is the code:

这是代码:

    public static void main(String[] args) {

    String url = "http://localhost:63003/api/sensors";
    String sensorname = "Simulated sensor";
    int currentTemp = 10;
    String dateString = "\" + "/Date(" + System.currentTimeMillis() + ")\" + "/";
    System.out.println(dateString);

    System.out.println("I'm going to post some data to: " + url);

    //Creating the JSON Object
    JSONObject data = new JSONObject();
    data.put("id", sensorname);
    data.put("name", sensorname);
    data.put("type", "Temperature");
    data.put("value", currentTemp);
    data.put("lastDateValue", dateString);
    JSONObject sensor = new JSONObject().put("sensor",  data);

    //Print out the data to be sent
    StringWriter out = new StringWriter();
    sensor.write(out);

    String jsonText = out.toString();
    System.out.print(jsonText);

    //Sending the object
    HttpClient c = new DefaultHttpClient();
    HttpPost p = new HttpPost(url);
    p.setEntity(new StringEntity(sensor.toString(), ContentType.create("application/json")));

    try {
        HttpResponse r = c.execute(p);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

The output of this program is as follows:

这个程序的输出如下:

\/Date(1382459367723)\/
I'm going to post some data to: http://localhost:63003/api/sensors
{"sensor":{"lastDateValue":"\/Date(1382459367723)\/","id":"Simulated sensor","name":"Simulated sensor","value":10,"type":"Temperature"}}

The issue here is that the JSONObject string still contains these escape characters. But when I print the string in the beginning it does not contain the escape characters. Is there any way to get rid of these? My service can't parse these..

这里的问题是 JSONObject 字符串仍然包含这些转义字符。但是当我在开头打印字符串时,它不包含转义字符。有没有办法摆脱这些?我的服务无法解析这些..

This is a sample of what I send with the rest client in chrome:

这是我在 chrome 中与其余客户端一起发送的示例:

 {"sensor":{"id":"I too, am a sensor!","name":"Willy","type":"Temperature","value":100.12,"lastDateValue":"\/Date(1382459367723)\/"}}

采纳答案by pburka

JSONObjectis correctly encoding the string. This pagedescribes how string literals are to be escaped in JavaScript (and, by extension, JSON). The following note is important to understanding what happens in your example:

JSONObject正确编码字符串。本页介绍了如何在 JavaScript(以及扩展名 JSON)中对字符串文字进行转义。以下注释对于理解示例中发生的情况很重要:

For characters not listed in Table 2.1, a preceding backslash is ignored, but this usage is deprecated and should be avoided.

对于表 2.1 中未列出的字符,前面的反斜杠将被忽略,但这种用法已被弃用,应避免使用。

Your example ("\/Date(1382459367723)\/") uses a preceding backslash before a /. Because /is not in table 2.1, the \should simply be ignored. If your service doesn't ignore the \, then it either has a bug, or is not a JSON parser (perhaps it uses a data format which is similar to, but not quite, JSON).

您的示例 ( "\/Date(1382459367723)\/") 在 a 之前使用前面的反斜杠/。因为/不在表 2.1 中,所以\应该简单地忽略。如果您的服务没有忽略\,那么它要么有错误,要么不是 JSON 解析器(也许它使用的数据格式类似于但不完全是 JSON)。

Since you need to generate non-conforming JSON, you won't be able to use standard tools to do so. Your two options are to write your own not-quite-JSON encoder, or to avoid characters which must be escaped, such as \and ".

由于您需要生成不符合标准的 JSON,因此您将无法使用标准工具来执行此操作。您的两个选择是编写自己的非 JSON 编码器,或者避免必须转义的字符,例如\"

回答by Rajaraman

@pburka is correct. If you want to send it in \/Date(1382459367723)\/format, try escaping the blackslash twice as below

@pburka 是正确的。如果您想以\/Date(1382459367723)\/格式发送,请尝试转义黑斜线两次,如下所示

String dateString = "\\" + "/Date(" + System.currentTimeMillis() + ")\\" + "/";

In the first pass, dateString will make it as \\/Date(1382459367723)\\/and finally JSONObject will add extra backslashes internally to it's buffer i.e \\\/Date(1382459367723)\\\/so that the blackslashes before / will be ignored according to JSON parsing rules and you would get the desired result i.e \/Date(1382459367723)\/

在第一遍中,dateString 将使其成为\\/Date(1382459367723)\\/,最后 JSONObject 将在内部向其缓冲区添加额外的反斜杠,即\\\/Date(1382459367723)\\\/,根据 JSON 解析规则,/ 之前的黑斜线将被忽略,您将获得所需的结果,即\/Date(1382459367723)\/