Wrong JSON array in JAVA, and added back slash in URL - java

I have the following JSON array which I use POST method to send it to BackEnd:
{"images":
[["https:\/\/storage.googleapis.com\/shelf-prove\/test1.jpg",
"https:\/\/storage.googleapis.com\/shelf-prove\/test2.jpg",
"https:\/\/storage.googleapis.com\/shelf-prove\/test3.jpg",
"https:\/\/storage.googleapis.com\/shelf-prove\/test5.jpg"]],
"skus":["
{\"id\":5179846254657536,\"coordinates\":\"137,447,692,438,690,610,140,617\",\"sku\":\"Biscotti\"}",
"{\"id\":5656058538229760,\"coordinates\":\"0,116,303,104,310,264,2,282\",\"sku\":\"Riso\"}",
"{\"id\":5765606242516992,\"coordinates\":\"140,614,675,610,673,751,145,755\",\"sku\":\"Succo\"}"],
"percentage":"33",
"model":5682617542246400,
"shelf":5660980839186432
}
in Java I try to get it as JSON array with the following code :
imagesToProcess = json.getJSONArray("images");
for(int i = 0; i < imagesToProcess.length(); i++){
String src="";
src = imagesToProcess.getString(i); }
the problem is that in java i see the value of the array as following:
[["https:\/\/storage.googleapis.com\/shelf-prove\/test1.jpg","https:\/\/storage.googleapis.com\/shelf-prove\/test2.jpg","https:\/\/storage.googleapis.com\/shelf-prove\/test3.jpg","https:\/\/storage.googleapis.com\/shelf-prove\/test5.jpg"]]
and in for loop, the value of each lement is like this:
[["https:\/\/storage.googleapis.com\/shelf-prove\/test1.jpg","https:\/\/storage.googleapis.com\/shelf-prove\/test2.jpg","https:\/\/storage.googleapis.com\/shelf-prove\/test3.jpg","https:\/\/storage.googleapis.com\/shelf-prove\/test5.jpg"]]
I don't know what's the problem!

The Reason why This is Happening:
A Valid JSON String will always Contain "\" before "/" for Representation.
See Image:
what JAVA Does here is Converts the JSON to a Valid JSON by adding "\" before "/" .
The Solution is to Process the String in JAVA and convert it to Original Format by removing '\' character occurences from String
For that You can Refer to Answer:
remove-all-occurrences-of-char-from-string

To answer your probably in order, you are trying to get the value for an array of array, this looks like an mistake of encoding since the first array is of 1 cells. So get the array in that cell then iterate, you have a correct code for that.
Then about the escaped character, you can see in the RFC 7159 - The JavaScript Object Notation (JSON) Data Interchange Format
From 7. Strings :
Any character may be escaped.
But there is no specification about which one, you can see in an example :
"Thumbnail": {
"Url": "http://www.example.com/image/481989943",
"Height": 125,
"Width": 100
},
The URL has no escape "/" so this is API specific.
There is know question about that problem on SO like :
JSON: why are forward slashes escaped?
Why is the slash an escapable character in JSON? [duplicate]

Related

How to avoid the ‘\’ when appying JSONObject.put operation of two strings to a JSONObject?

The codes is like the following:
JSONObject solution = new JSONObject();
variableName = "TEST"
System.err.println("1:"+value);
solution.put(variableName, value);
System.err.println("2:"+solution);
Here is the output result:
1:{"min":10,"max":40}
2:{"TEST":"{\"min\":10,\"max\":40}"}
How can I get rid of the annoying '\'?
Thank you very much!
The reason why you are getting \ in your print line is because it is escaping the " character which is used in value. There's nothing wrong with this, it simply signifies that \" is not terminating the string and is instead a value part of that string.
Usage of double quotations is valid JSON, not single quotes - see related Q here.
But if you really want to, if you create value like this:
JSONObject value = new JSONObject("{'min':10,'max':40}");
Then you should get the desired output from your existing code:
1:{"min":10,"max":40}
2:{"TEST":{"min":10,"max":40}}

Why java Path.Separator in JSON file format is switched to \?

I want to put a picture path in a jsonObject and pass it to javascript, in java i do
JSONObject assets = new JSONObject();
assets.put("media",PropertyLoader.getStringValue("PICTURE_DIRECTORY") + "/"+leventPhoto.getFile().getName());
When i get it in the jsp file in javascript it appears like this:
"media":"C:\/Users\/joao\/workspace\/.metadata\/.plugins\/org.eclipse.wst.server.core\/tmp1\/wtpwebapps\/RememberMeServer\/images\/02.jpg"
What can i do to make the separator appear well formated inside JSONObject displayed in javascript?
By the time the data has been read within Javascript, it will have the appropriate name. This is just an escape sequence, which doesn't change the value of the data. For example, in a Javascript console:
var x = "foo\/bar";
var y = "foo/bar";
x == y // true
I'm surprised that the forward slashes are being escaped - just "C:/Users/joao/..." would work fine - but it shouldn't make any difference to the actual value.
It is just escaping the /, it is not changing the string itself.
As to why forward slashes are being escaped, you may want to check out this question:
Allowing / helps when embedding JSON in a tag, which doesn't allow </ inside strings, like [user] points out.

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

Android Decode JSON Encoded by PHP file

I've created a JSON string in a php file. I've then used json_encode($jsonStr) to encode the string.
$jsonStr =
"{
\"statusCode\": 0,
\"errorMsg\": \"SUCCESS\",
\"id\": $id,
\"message\": ".json_encode($message).",
\"author\": \"$author\",
\"showAfter\": \"$date\"
}";
I'm making a network call in java (Android) to get this string. My next step is to decode the string, however this doesn't seem to be working too well.
Here is a sample of what I'm trying to decode in my Android code:
{\n\t\t\t\t\"statusCode\": 0,\n\t\t\t\t\"errorMsg\": \"SUCCESS\",\n\t\t\t\t\"id\": 1,\n\t\t\t\t\"message\": \"This is a message.\",\n\t\t\t\t\"author\": \"Anonymous\",\n\t\t\t\t\"showAfter\": \"2013-06-18 01:19:49\"\n\t\t\t}
Yes it is riddled with encoded line breaks and such. I assumed that might be the issue so I took those out, however I still have issues, so I'm guessing there must be something bigger going on.
I know this is valid JSON because I'm able to decode it and use it in a javascript based website.
How can I accomplish this on Android/Java?
Your original JSON string (the one you show in your first snippet) looks to be valid JSON already. You must not encode it. Encoding it is what makes it invalid JSON, transforming every tab into \t, and every new line into \n.
Read the documentation of json_encode carefully.

can not parse json array from php

my array returns the following valid json.
{"usernames ":["a","b","c"]}
In Java I am trying to retrieve the value of the array by the following method. However I fail.
JSONArray usernames = json.getJSONArray("usernames");
The key ends with a space. try
JSONArray usernames = json.getJSONArray("usernames ");
EDIT:
It would be better to lose the space in your php script.
remove the space in your code : "usernames " ---> "usernames"

Categories