Write correctly an URL in JSON with Java - 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

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:
("solidus" is a fancy term for slash)

Related

How can I extract url from json data with escaped "\" in java

I need to extract url from json filed. (replace it with "" and do not break the json format), so that there's no url in json.
the url looks in this way
"source":"\u003ca href=\"http:\/\/twitter.com\/download\/iphone\",
"profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/3475536942\/2b0ccd9e42754adf7e22947037dd8c34_normal.jpeg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/488849893\/1364691799",
...
I noticed that there's "\" in the url to escape the string, I don't know how to deal with it while writing the regex.
Simply use a lightweight JSON parser such as this reference implementation in Java
To overwrite, say, the source property to "blah", it is possible to do things as simple as
String newJsonString = new JSONObject(originalJsonString).putString("source","blah").toString();

JSON object adding extra back slash

What i am doing currently creating json object and passing to volley for service call, its placing back slash in jsonObject in key value result is getting 404. following is my code and creating jsonObject.
JSONObject params = new JSONObject();
params.put("user_name", "syedshah11#gmail.com");
params.put("password", "6e7a0497daffa4554cc28973bc129632");
params.put("key", "ly9jCDu03/1:3M1");
And as i debuged the josnObject adding extra \ (forward slash in my key json object thats why service break through as 404) following is json getting through debug.
{
"password": "6e7a0497daffa4554cc28973bc129632",
"user_name": "syedshah11#gmail.com",
"key": "ly9jCDu03\/1:3M1"
}
So how to remove this \ extra forward slash as instead of this ly9jCDu03/1:3M1 its making ly9jCDu03\/1:3M1 any help could be appreciated.
Thanks in Advance
Java is encoding your JSON string for sending to end point. Slash (/) is not an issue, if request not build with proper manners and there is any problem at Java end then you receive 500 Internal Server Error or volley error.
Be confident on your code and check service.
when json convert key value to string "ly9jCDu03/1:3M1" it adds extra '\' to represent the '/' as '/' is a special character and to represent that u need '\'
it is just like when u want to print '/n' in c++ u need to add extra '\'

How to convert Json string with escape characters to json in Android

I am getting the following json as a reponse of a rest call. I am unable to parse it. Replacing "\" with "" doesn't work as the string contains many escape characters like "\n".
"[{\"message_id\":50870,\"message\":\"4d074d54-6e08-a140-fb7a-ee1300b01fbf.png\"},
{\"message_id\":50823,\"message\":\"1\\n2\\n3\\n4\\n5\\n6\"},{\"message_id\":50341,\"message\":\"I am getting a \\\"Server Error\\\" }]"
I have tried JsonTokener, UrlDecoder, but nothing seems to work.
I have also tried using
JsonString.replace ("\\"", "\"");
This works but is there a better way for conversion
JSONSerialiser serialiser = new JSONSerialiser();
String jsonOutput= serialiser.include("id","message").exclude("*").serialize(javaobject);
JSONObject jObject = JSONFactoryUtil.createJSONObject(jsonOutput);

Jackson not escaping quotes in JSON

I'm trying to put a json in a javascript file in java, but when I write the json to a string, the string doesn't appear to be a valid json for javascript; it is missing some escapes. (This is happening in a string in the json which I formatted as a faux json.)
For example, this would be a valid json in my javascript file:
{
"message":
"the following books failed: [{\"book\": \"The Horse and his Boy\",\"author\": \"C.S. Lewis\"}, {\"book\": \"The Left Hand of Darkness\",\"author\": \"Ursula K. le Guin\"}, ]"
}
Here's what I get, though, where the double quotes aren't escaped:
{
"message":
"The following books failed: [{"book": "The Horse and his Boy","author": "C.S. Lewis"}, {"book": "The Left Hand of Darkness","author": "Ursula K. le Guin"}, ]"
}
I get the second result when I do this:
new ObjectMapper().writer().writeValueAsString(booksMessage);
But when I write it directly to a file with jackson, I get the first, good result:
new ObjectMapper().writer().writeValue(fileToWriteTo, booksMessage);
So why does jackson escape differently when writing to a file, and how do I get it to escape like that for me when writing to a string?
The writeValue() methods of the ObjectWriter class encode the input text.
You don't need to write to a file. An alternative approach for getting the same string could be:
StringWriter sw = new StringWriter();
new ObjectMapper().writer().writeValue(sw, booksMessage);
String result = sw.toString();
I added
booksJson = Pattern.compile("\\\\").matcher(booksJson).replaceAll("\\\\\\\\");
which escapes all the escape characters. That way when I write it to file and it removes the escapes, I still have the escapes I need. So turns out my real question was how to write to file without Java escapes being removed.
I'm very late to the party but I faced a similar problem and I realized it was not a problem with Jackson or my data. It was Java. I was reading from a JSON file and then trying to write it into a template HTML file.
I had a line my original JSON like yours, something like:
{"field" : "This field contains what looks like another JSON field: {\"abc\": \"value\"}"}
And when I wrote the above to a string, the backslash before the quotes in abc and value disappeared. I noticed that the contextual help for String.replaceAll mentioned something about Matcher.quoteReplacement. I went from this:
template = template.replaceAll("%template%", jsonDataString);
to this:
Pattern pattern = Pattern.compile("%template%");
Matcher matcher = Pattern.matcher(template);
matcher.replaceAll(matcher.quoteReplacement(jsonDataString));
Problem solved.
Matcher.quoteReplacement

Java : How to assign Json formated String to Java String?

I have a big json string which i will be getting as a request from the UI , which will be converted to a String and parsed .
I want to simulate the similar environment for testing locally , so for this purpose i captured the JSon format.
Currently i am manually adding "/" to this big json string .
Is there any other way to achieve this ??
For example i got this json
{"age":29,"messages":["msg 1","msg 2","msg 3"],"name":"Preethi"}
and converted that into
String str = "{\"age\":\"29\",\"messages\":[\"msg 1\",\"msg 2\",\"msg 3\"],\"name\":\"mkyong\"}";
Is there any other way to achieve this ??
On the client-side, do a search and regex "replace all" of double-quotes into single quotes on the desired form field before actually sending the request.
Actually, Java doesn't have verbatim string literals.
If you want a Java-like (and Java-VM-based) language that does, however, you might want to look at Groovy which has various forms of string literal.
we have in build method to convert jsonObject to string. Why don't you use that.
JSONObject json = new JSONObject();
json.toString();

Categories