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.
Related
I have a string that is base64 encoded. It looks like this:
eyJibGExIjoiYmxhMSIsImJsYTIiOiJibGEyIn0=
Any online tool can decode this to the proper string which is {"bla1":"bla1","bla2":"bla2"}. However, my Java implementation fails:
import java.util.Base64;
System.out.println("payload = " + payload);
String json = new String(Base64.getDecoder().decode(payload));
I'm getting the following error:
payload = eyJibGExIjoiYmxhMSIsImJsYTIiOiJibGEyIn0=
java.lang.IllegalArgumentException: Input byte array has incorrect ending byte at 40
What is wrong with my code?
Okay, I found out. The original String is encoded on an Android device using android.util.Base64 by Base64.encodeToString(json.getBytes("UTF-8"), Base64.DEFAULT);. It uses android.util.Base64.DEFAULT encoding scheme.
Then on the server side when using java.util.Base64 this has to be decoded with Base64.getMimeDecoder().decode(payload) not with Base64.getDecoder().decode(payload)
I was trying to use the strings from the args. I found that if I use arg[0].trim() that it made it work. eg
Base64.getDecoder().decode(arg[0].trim());
I guess there's some sort of whitespace that gets it messed up.
Maybe too late, but I also had this problem.
By default, the Android Base64 util adds a newline character to the end of the encoded string.
The Base64.NO_WRAP flag tells the util to create the encoded string without the newline character.
Your android app should encode src something like this:
String encode = Base64.encodeToString(src.getBytes(), Base64.NO_WRAP);
I am developing a small mail client in the Java Play Framework and I'm using SendGrid for the e-mails. When an e-mail is received, it gets posted to a url and I then parse the posted form using JsonNode. Now the problem is the "to", "from", "subject" fields of that form are automatically converted by SendGrid to UTF-8. Now comes the problem: apparently, the email message body is encoded in "ISO-8859-1". And I need to convert that String to "UTF-8". I already tried several ways of doing so, but most probably I'm doing something very wrong, since I always get strange characters for French or German words containing accents/umlauts (Example "Zürich" comes out as "Z?rich". The code I'm using for the conversion is the following:
byte[] msg = message.getBytes("ISO-8859-1");
byte[] msg_utf8 = new String(msg, "ISO-8859-1").getBytes("UTF-8");
message = new String(msg_utf8, "UTF-8");
Could you, please, suggest a solution? Thank you very much in advance!
Ok so I managed to get the raw byte request from SendGrid using the annotation and created the java String with the correct encodings:
#BodyParser.Of(BodyParser.Raw.class)
public static Result getmail() {
...
}
Now the problem is that for retrieving the file attachments from the request I would need the request to be parsed as MultipartFormData. With the annotation above set, I get a NullPointerException when calling, which was predictable:
request().body().asMultipartFormData().getFiles()
Does any of you have any idea on how I could get the same request again, but parsed with the #BodyParser.Of(Bodyparser.MultipartFormData.class) ? So I kind of need to combine the two annotations or find a way to convert the byte[] I get from the Raw parser to a MultiFormData. Thanks!
When I am sending a TextEdit data as a JSON with data as a combination of "; the app fails every time.
In detail if I am entering my username as anything but password as "; the resultant JSON file looks like:-
{"UserName":"qa#1.com","Password":"\";"}
I have searched a lot, what I could understand is the resultant JSON data voilates the syntax which results in throwing Default exception. I tried to get rid of special symbol by using URLEncoder.encode() method. But now the problem is in decoding.
Any help at any step will be very grateful.
Logcat:
I/SW_HttpClient(448): sending post: {"UserName":"qa#1.com","Password":"\";"}
I/SW_HttpClient(448): HTTPResponse received in [2326ms]
I/SW_HttpClient(448): stream returned: <!DOCTYPE html PUBLIC ---- AN HTML PAGE.... A DEFAULT HANDLER>
Hi try the following code
String EMPLOYEE_SERVICE_URI = Utils.authenticate+"?UserName="+uid+"&Email="+eid+"&Password="+URLEncoder.encode(pwd,"UTF-8");
The JSON you provided in the Question is valid.
The JSON spec requires double quotes in strings to be escaped with a backslash. Read the syntax graphs here - http://www.json.org/.
If something is throwing an exception while parsing that JSON, then either the parser is buggy or the exception means something else.
I have searched a lot, what I could understand is the resultant JSON data voilates the syntax
Your understanding is incorrect.
I tried to get rid of special symbol by using URLEncoder.encode() method.
That is a mistake, and is only going to make matters worse:
The backslash SHOULD be there.
The server or whatever that processes the JSON will NOT be expecting random escaping from a completely different standard.
But now the problem is in decoding.
Exactly.
Following provided JSON can be parsed through GSON library with below code
private String sampledata = "{\"UserName\":\"qa#1.com\",\"Password\":\"\\\";\"}";
Gson g = new Gson();
g.fromJson(sampledata, sample.class);
public class sample {
public String UserName;
public String Password;
}
For decoding the text I got the solution with..
URLDecoder.decode(String, String);
I use similar code as its shown here in the question.
Java and AppStore receipt verification
But I still end up getting
{"status":21002, "exception":"java.lang.IllegalArgumentException"}
Can it be a problem at Base64 encoding?. Do I have to convert the base64 encoded string into hex or something else?.
What i post is similar to following
{"receipt-data" : "eyJzaWduYXR1cmUiOiJBbjNJVER0VVNmZWNhaGMxR.....
The problem was at Base64 encoding inside Java. When I do the encoding inside IOS and use that as the request from server without any encoding in Java, then it worked.
I had a similar problem and was receiving the java.lang.IllegalArgumentException from Apple when trying to validate a receipt on my server. The problem was that my base64 encoding logic was inserting lines breaks into the encoded string. Once I updated my code to ensure no new line breaks were being inserted into the encoded string, I was able to successfully verify my receipts against Apple's servers.
I m trying to match java base64 code in php. But getting inconsistent result.
Java base64 encode
encMessage = URLEncoder.encode(new Base64(-1).encodeToString(encrypted),"UTF8");
Java decode
message = URLDecoder.decode(message,"utf8");
Above code java encode code return the string which i have to decode and decrypt in php
PHP base64 decode
$message = utf8_decode(urldecode($encrypted));
$message = base64_decode($message);
PHP encode
$encMessage = base64_encode($encrypted);
$encMessage = utf8_encode(urlencode($encMessage));
Results:
java:
KO%2F%2B%2Bzbp5z8oCdvZn62jb72kseT%2Bem8hYUZY0IuB9zo%3D
php:
KO%2F%2B%2Bzbp5z8oCdvZn62jb3CVVVXsV%2Bws2kDOmKK%2BPEc%3D
src : https://gist.github.com/944269
I had this problem between CSharp and Java, and found that URL encoding things was the culprit. What I did in my work around was basically re-encrypt the data with a newly generated public key until I got one that didn't need URL encoding. Not a great solution, but it works, it averages 2 tries to get it right, but I've seen it taking up to 15 tries to do it, either way we're still talking milliseconds, and it works reliably.
YMMV