jjmartinez
jjmartinez

Reputation: 807

Write correctly an URL in JSON with Java

I need to write an attribute on a JSON document, and this attribute is an URL

This is my code:

String url = "http://localhost:1028/accumulate";
JSONObject cabecera = new JSONObject();
cabecera.put("reference", url);

But when I create the JSON,this attibute is writted in this way:

"reference":"http:\/\/localhost:1028\/accumulate",

So, the service that receives the JSON String, it's sending me an error:

<subscribeContextResponse>
  <subscribeError>
    <errorCode>
      <code>400</code>
      <reasonPhrase>Bad Request</reasonPhrase>
      <details>JSON Parse Error: <unspecified file>(1): invalid escape sequence</details>
    </errorCode>
  </subscribeError>
</subscribeContextResponse>

What is the correct way to write the URL??

Thanks in advance

Upvotes: 1

Views: 4106

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074305

But when I create the JSON,this attibute is writted in this way:

"reference":"http:\/\/localhost:1028\/accumulate",

That's fine, the backslashes are harmless, whatever you're using to serialize to JSON is just being a bit hyper with its escapes. The string represented by the above contains no backslashes at all, just slashes. \/ inside a JSON string is exactly the same as /, as we can see from the highlighted rule from http://json.org:

enter image description here

("solidus" is a fancy term for slash)

Upvotes: 5

Related Questions