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();
Related
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();
I used json_encode(); to convert string to json in php and then response it to android but I can't use the response, how can I convert the json to string?
when I display the response it shows this :
"{\n'OK': \n[\n{\n'Name': 'MyName',\n'Gender':'Male'\n}\n]\n}"
what shall I do?
thank you
Since you're just converting a string to json, you're not returning a JSONObject or JSONArray, according to: http://php.net/manual/en/function.json-decode.php
If you must return a string, you may have to use some json library or write your own parser.
If that doesn't sound appealing, I recommending returning a JSONObject or JSONArray with one element.
For example:
php
echo json_encode( array('result' => 'the string you are encoding') );
java
JSONObject json = new JSONObject( encodedStringResponseFromPhp );
String theStringYouEncoded = (String) json.get( "result" );
You'll need to add a throws JSONException to the function you add this java code too or put it inside a try catch block.
Have you tried using a JSON-Library like https://code.google.com/p/json-simple/? Looks like you need some help decoding the string.
Edit: You should use the json2.js library from Douglas Crockford. It provides some extra features and better/older browser support.
Read more...
I am using org.json to parse and write json. While serializing, i.e converting to string, I see json object adds an extra escape character. How can be this be avoided, if possible ?
String jsonStr = "{\"AD\":\"</p>\"}";
JSONObject jsonObject = new JSONObject(jsonStr);
System.out.println(jsonStr);
System.out.println(jsonObject.toString());
Output:
{"AD":"</p>"}
{"AD":"<\/p>"}
A number of other StackOverflow posts point out that this happens because (1) it is allowed by the JSON spec, and (2) it allows the JSON string to be inserted as-is into certain XML/HTML contexts that would otherwise not allow strings with "</" inside them.
If this causes problems, I would seek out A Better Java JSON Library--one that lets you define more character-escaping options.
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.
I am creating a JSONArray and parse it to a String, but as it even contains Strings instead of code it doesn't output as I need it.
for(Place place: places){
locations.put("new google.maps.LatLng("+place.getContactData().getLatitude()+","+place.getContactData().getLongitude()+")");
}
return locations.toString();
It outputs as: ["new google.maps.LatLng(53.5608,9.96357)","new google.maps.LatLng(53.5608,9.96357)"] but I need it without quotation marks like [new google.maps.LatLng(53.5608,9.96357),new google.maps.LatLng(53.5608,9.96357)] to be correctly interpreted by javascript.
Another method would be:
create an array with just the coordinates:
for(Place place: places){
JSONObject obj = new JSONObject();
obj.put("lat",place.getContactData().getLatitude());
obj.put("lng",place.getContactData().getLongitude());
locations.put(obj);
}
and then in javascript:
var places = (yourPlacesJson);
var placeObjects = [];
for(var i=0;i<places.length;i++)
{
placeObjects[placeObjects.length] = new google.maps.LatLng(places[i].lat,places[i].lng);
}
JSON only supports plain-old-data. It can't include any executable code (a new is executable code). This is by design - when JSON would be able to include executable code you would have to be much more carefully with importing JSON from an untrusted source.
All you can do is pass javascript code as strings and eval() it on the JS side after parsing the JSON.
Also you could use Regular expressions to remove the ", if you parse the json to another language
i had a similar problem, the way i made this work:
instead of writing the javascript before the json conversion, insert a placeholder.
locations.put("%mapsPlaceholder1%");
then after filling the array with placeholders, do:
locations.toString().replaceFirst("\"%mapsPlaceholder1%\"","yourJsCode");
something like that
you could also just create the array string manually