I need to send a date in JSON. The date string should look like this:
"2013/5/15"
Instead , JSONObject.toString escapes it as follows:
"2013\ /5\ /15"
I understand that this is done to allow json strings inside scripts tags, as this question explains:
JSON: why are forward slashes escaped?
But in my case I don't need it. In fact the server is returning an error. The server is not dealing with this and I can't fix the server, so I must fix it in the mobile client code.
I could do a String.replace after serializing it, but what if I actually wanted to include the "\ /" string in any other part of the JSON?
Is there a way to serialize a JSON object without escaping slashes? (If possible, without escaping anything)
I finally opted for the quick and dirty trick of replacing the escaped slashes in the serialized string before sending it to the server. Luckily, JSONObject also escapes backslashes, so i must also unscape them. Now if I wanted to send "\ /" intentionally the escaped string would be "\\/" and the result of replacing is the original string as intended.
That behavior is hard-coded into JSONStringer.java, see method private void string(String value), line 302+.
It should be possible to copy class JSONStringer and implement your own version of value(Object) (line 227+). Then implement your own version of JSONObject.toString() in a utility class and use your own JSONStringer instead of the original.
EDIT: Subclassing JSONStringer won't be easy because value() calls a private method beforeValue() that cannot be accessed.
jsonObjSend.toString().replace("\\\\","")
Worked for me. A bit dirty trick but seems no other solution.
I had a similar problem with JSONObject "put" when dealing with data for an image that was encoded into a adat Uri "data:image/png;base64,.....". The put function would add another slash to change the format to "data:image/png;base64,.....". It seems that the source of the problem is a string value check within the JSONObject "put" function that adds the extra slashs. One could maybe overload the function or extend the class but I found the easiest way is to add a unique string such as guid and then replace that guid with your Uri string after the calling the toString() function of your JSONObject.
JSONObject userJson = new JSONObject();
String myimageUri = "data:image/png;base64,XXXDATAXXX";
userJson.put("imageUri", "b0c8f13d-48b1-46b4-af28-4e2d8004a6f8");
userJson.toString().replace("b0c8f13d-48b1-46b4-af28-4e2d8004a6f8", myimageUri);
I was getting similar slashes when I used
val dateString = Gson().toJson(dateObject).toString()
You need to deserialize this json.
JSONObject(dateString)
The problem is with the imports.
Use below imports :-
import org.json.JSONException;
import org.json.JSONObject;
Instead of import org.json.simple.JSONObject;
It will work.
Related
I pass some parameters in ajax URL and want to get that parameters by request.getParameter(); in controller if that parameters have some special character like #,%,&, etc. then how to get it?
String xyz = new String(request.getParameter("XYZ").getBytes("iso-8859-1"), "UTF-8");
You have two options:
1.Encode values to JSON before sending, and decode them on server.
Use javascript method encodeURIComponent https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
I found best solution after spending couple of hours use
((String[])request.getParameterMap().get("paramname"))[0]
which gives me param value with special charater
Can you anyone help me with problem of parsing args in java?
I need to read JSON data by args in two formats(file, text arg). If an arg is path to file with JSON text, it's working.
In main method I'm reading args:
public static void main(String[] args){
String argText = args[1]
}
But if I'm put to arg some JSON text (for example: {"server1":{"dname":"www.server.com","lat":"40","lng":"17"}) it's problem with quotes, because in
String argText is stored text without quotes:
System.out.println("Text: " + argText);
Text: {server1:{dname:www.server.com,lat:40,lng:17}
And method for parsing JSON:
public static JSONObject parseJSON(String argText){
if (text.contains("{")){
//arg is text and I want to store it as JSONObject
// how to store text with "
} else {
//argText is file....
// read file, put in new JSONObject
// it works without any problems.
}
return JsonObject
}
I don't know it is the good way to read input args, but for file it's working and I would to add reading form the text.
If argText contains escaped quotes \\\" everythig is OK, but I don't have text in these format.
EDIT:
So I don't have problem with parsing JSON bud I need some method that doing:
public static void(String quotedText){
//do something...
System.out.print("Output: " + text);
}
with in/out:
< '"text":"val1","val2","val3"'
Output: "text":"val1","val2","val3"
In Win system.out.print is:
'Output: text:val1,val2,val3'
The quotes are munged by the shell; put the whole string in single quotes for that to work. If your utility is launched by some other program, fix that program to escape everything, or transport it using stdin.
If using library does not suit your needs, you can make a simple method to covert it.
Add " after every {, before every }, and both before and after every , and :.
There might be some ambiguity with those chars, but that why quotes are supposed to be there at first place.
Maybe you should use some standard library for parsing JSON, it will really save you a lot of time. JSON isn't that simple that you can just treat it like a simple string.
Try:
http://jackson.codehaus.org/
https://code.google.com/p/json-simple/
You should try a standard library to parse JSON, like Alexander said.
There are some out there that convert JSON into Java objects. I personally like XStream. Try this JSON with Xtream tutorial
With it, you can define your own Java objects and use the library to convert JSON to those objects and from the objects to JSON. No need to create your own parser.
I recommend this simple and widely used library: GSON
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 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();
I am trying to send the following parameters to a server through HTTP POST:
["my_session_id","{this=that, foo=bar}"]
But the server is returning a parse error because of the quotes around the hash.
I am trying to remove them with a regex like so:
params.replaceAll("\\\"\\{", "\\{");
params.replaceAll("\\\"\\}", "\\}");
In all honestly I have no idea what I'm doing. Please help.
Thanks in advance!
There's two issues here: First, you're not re-assigning the string. Strings are immutable in Java (cannot be changed), so you must assign the result. Second, you're replacing "} instead of }".
Here's what I used:
String params = "[\"my_session_id\",\"{this=that, foo=bar}\"]";
params = params.replaceAll("\\\"\\{", "\\{");
params = params.replaceAll("\\}\\\"", "\\}");
System.out.println(params);
Which prints out:
["my_session_id",{this=that, foo=bar}]
PS: Bit of advice, use JSON. Android has excellent JSON handling, and it is supported in PHP as well.
Is there a reason you are using the regular expression replaceAll? Alternatively, you might try:
String parameters = parameters.replace("{", "\\{").replace("}", "\\}");