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("}", "\\}");
Related
I'm trying to create an MUnit test that mocks an HTTP request by setting the payload to a JSON object that I have saved in a file. In Mule 3 I would have just done getResource('fileName.json').asString() and that worked just fine. In Mule 4 though, I can't statically call getResource.
I found a forum post on the Mulesoft forums that suggested I use MunitTools::getResourceAsString. When I run my test, I do see the JSON object but with all the \n and \r characters as well as a \ escaping all of the quotation marks. Obviously this means my JSON is no longer well formed.
Ideally I would like to find a reference for MunitTools so that I can see a list of functions that I can call and maybe find one that does not add the escape characters, but I haven't had any luck. If anybody knows of a some reference document that I can refer to, please let me know.
Not being able to find a way to return the data without the extra characters, I tried replacing them via dataweave. This is fine when replacing \n and \r, but as there are also more \s in front of each double quote and I can't seem to make these go away.
If I do this...
replace (/\/) with ("")
...I get an error. A co-worker suggested targeting the each \" and replacing them with ", but that's a problem because that gives me """. To get around this, I've tried
replace(/\"/) with "\""
...which does not cause any errors, but for some reason it reads the \ as a literal so it replaces the original string with itself. I've also tried...
replace(/\"/) with '"'
...but that also results in an error
I'm open to any other solutions as well.
Thanks
--Drew
I had the same concern so I started using the readUrl() method. This is a DataWeave method so you should be able to use it in any MUnit processor. Here is an example of how I used it in the set event processor. It reads the JSON file and then converts it into Java for my own needs but you can just replace java with JSON for your needs.
<munit:set-event doc:name="Set Event" doc:id="e7b1da19-f746-4964-a7ae-c23aedce5e6f" >
<munit:payload mediaType="application/java" value="#[output application/java --- readUrl('classpath://singleItemRequest.json','application/json')]"/>
</munit:set-event>
Here is the documentation for readUrl https://docs.mulesoft.com/mule-runtime/4.2/dw-core-functions-readurl
Hope that helps!
Follow this snippet (more specifically the munit-tools:then-return tag):
<munit-tools:mock-when doc:name="Mock GET /users" doc:id="89c8b7fb-1e94-446f-b9a0-ef7840333328" processor="http:request" >
<munit-tools:with-attributes >
<munit-tools:with-attribute attributeName="doc:name" whereValue="GET /users" />
</munit-tools:with-attributes>
<munit-tools:then-return>
<munit-tools:payload value="#[read(MunitTools::getResourceAsString('examples/responses/anypoint-get-users-response.json'), "application/json")]" />
</munit-tools:then-return>
</munit-tools:mock-when>
It mocks an HTTP request and returns a JSON object using the read() function.
In JMeter, I used a Regular Expression Extractor to extract part of an HTML response. I then passed that to a BeanShell Post Processor. However, having trouble replacing \x2D to -. Is there a way to do this or perhaps do I need to extract the response as
String yourvar = vars.get("accessToken");
String anotherVar = yourvar.replace("data.access_token = '","");
String finalAccessToken = anotherVar.replace("\x2D","-");
vars.put("finalAccessToken",finalAccessToken);
It is not liking the "\x2D" part. It works if I find \x2D but the original string only has .
You need to escape your target String parameter.
final String finalAccessToken = anotherVar.replace("\\x2D", "-");
If it's not what you're asking for, add more info to the question. That's all what I was able to understand.
It is recommended to use JMeter's built-in test elements where possible. In particular your case you might be interested in __strReplace() custom JMeter Function
Install Custom JMeter Functions bundle using JMeter Plugins Manager
Use the following expression to make the replacement:
${__strReplace(${anotherVar},\\\x2D,-,)}
If you want to go for scripting - make sure to use JSR223 PostProcessor and Groovy language. Be aware that you will still need to escape backslash with another backslash like:
String finalAccessToken = anotherVar.replace("\\x2D","-");
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
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.
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);