How can I decode this JSON String which has been received as a parameter via the ajax call. This String is basically a Javascript Array which has been passed using JSON.stringify.
The format received at my Java End is something like this.
%5B%22Name%22%2C%22Vivek%22%2C%
how can i decode this String so that I can create a JSONArray from it using
JSONArray.fromObject
because passing the above mentioned format throws an error
It looks like it is URL encoded. Try decoding it before parsing.
String decodedString = java.net.URLDecoder.decode("%5B%22Name%22%2C%22Vivek%22%2C%", "UTF-8");
JSONArray json = new JSONArray(decodedString);
Related
I have the following string which (as far as I know) is in a valid format
[
{
"name":"John Doe"
},
{
"name":"Jane Doe"
}
]
After calling the following:
return new JSONArray(jsonString);
With jsonString being the JSON given above. I get the following error:
org.json.JSONException: Value jsonString of type java.lang.String cannot be converted to JSONArray
Any ideas why the parser won't accept the string?
Edit
The problem has been solved. The array was encoded as a string in the JSON output. I first retrieved the string with the getString(param) method instead of trying to convert it directly with getJsonArray, then converted the string to the json array.
The JSON appears to be valid on jsonlint.com. But a quick Google search reveals that there are other possible sources of the problem:
Are you specifying UTF-8 encoding and decoding the string before parsing it as a JSON object?
Do you need to add a json library to your project?
The problem has been solved. The array was encoded as a string in the full JSON output. I first retrieved the string with the getString(param) method instead of trying to convert it directly with getJsonArray, then converted the string to the json array.
I want to get the value of String and I am trying to put the string in the JSON and get it. The format of string is "key=value&key1=value". The code I am using is:
JSONObject json = new JSONObject(String);
String value = json.get("key").toString();
That string is url encoded not json formatted.
You can use a url decoder instead. Something like http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html might work for you.
I used Patterns and Matchers and it worked perfectly. Thank you.
I am struggling with some issue related with http, java and the stackexchange API
consider the following url as string:
private static final String URLSTRING_2 = "http://freegeoip.net/json/";
if I write this url in my browser I get this answer as json:
now im trying to do that with java and only native libs, for that am using the snippet below wich is working so far so good...
If I parse the json and i try to get the value for the key "country_name" then the snippet prints as spected "Singapore"
public static void main(String[] args) throws Exception {
// Connect to the URL using java's native library
final URL url = new URL(URLSTRING_2);
final HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// Convert to a JSON object to print data
final JsonParser jp = new JsonParser(); // from gson
final JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); // Convert the input stream to a json
// element
final JsonObject rootobj = root.getAsJsonObject(); // May be an array, may be an object.
final String country = rootobj.get("country_name").getAsString(); // just grab the zipcode
System.out.println("country_name: " + country);
}
Now my question:
if I do the same with this link
https://api.stackexchange.com//2.2/users/22656?order=desc&sort=reputation&site=stackoverflow&filter=!T6oHjO_RIWkfWpoL5g
my browser outputs the following json:
but if I try to parse the json I get an exception because am getting from the request this:
ý•#‡ž¼ÚRìØ1ôX`»v?±h[‹-¹’/+ò........
for something that is not even human readable...
do you know why?
Thanks in advance
The StackOverflow API GZIP-compresses its response. The reason you see that string of non-human-readable characters is that you are trying to read GZIP-compressed data without first decompressing it.
Your browser is capable of reading this header and doing the decompression itself. Your code isn't yet.
You can confirm that GZIP compression is used by displaying the value of the Content-Encoding header in the response. Adding the line
System.out.println(request.getContentEncoding());
will print out
gzip
Fortunately, fixing the problem is fairly straightforward. You need to wrap the InputStream you get from the request in a GZIPInputStream:
final JsonElement root = jp.parse(new InputStreamReader(new GZIPInputStream((InputStream) request.getContent()))); // Convert the input stream to a json
However, instead of the built-in Java classes, I'd recommend using a library such as Apache HTTPComponents Client for making your HTTP requests. In particular, a library such as this will automatically detect the content-encoding and do the decompression for you.
In my application I retrieve search results in JSON format from an external tool called Google Search Appliance(GSA).
The JSON result from GSA is very large and therefore I prefer to modify the GSA JSON result into something more suitable for displaying on my webpage.
If I directly display the GSA JSON result without formatting it in my java code I'm not facing any encoding issues on my webpage.
But if I format the large GSA JSON result into a suitable JSON format in my servlet java code I'm facing encoding problems.
Example - “All Access Pass” gets displayed as ÂAll Access PassÂ.
I return the modified json from my servlet to the webpage use the following code -
response.setContentType("application/json;charset=UTF-8");
I have tried to change the charset to iso-8859-1 but it does not make any difference.
I edit my original JSON in the following manner -
String responseText = getMethod.getResponseBodyAsString();
JSONObject resultJSON = new JSONObject();
try {
JSONObject jsonObj = new JSONObject(responseText);
JSONArray resultJsonArray = jsonObj
.getJSONArray("RES");
JSONObject searchResultJSON = null;
for (int iCnt = 0; iCnt < resultJsonArray.length(); iCnt++) {
searchResultJSON = new JSONObject();
JSONObject obj = resultJsonArray.getJSONObject(iCnt);
JSONObject metaTagObj = obj
.getJSONObject("MT");
if (metaTagObj.has(("title"))) {
searchResultJSON.put("title",metaTagObj.get("title").toString());
}
resultJSON.accumulate("RES", searchResultJSON);
}
response.setContentType("application/json;charset=UTF-8");
response.getWriter().print(resultJSON);
}catch(JSONException e){}
The modification to the original JSON which I'm going here can be done in JavaScript which would solve my problem but it is something which I do not want to do.
Is there a way to find out the encoding format of the text in the original GSA JSON?
How can I avoid the java code from changing the text encoding in the original GSA JSON?
Please help me understand what is going on here and how I can avoid this problem.
The text encoding problem was happening because the call which is made to the GSA server using Apache HTTP Client was using a default content encoding character set of iso-8859-1 but the GSA server expected the HTTP Client request and response to be in UTF-8 encoding.
This problem got resolved after setting the encoding for HTTPClient -
HttpClient httpClient = new HttpClient();
httpClient.getParams().setContentCharset("UTF-8");
And the servlet response encoding to
response.setContentType("application/json;charset=UTF-8");
i first create a Json String with
String myJsonString = new Gson().toJson(myElement);
this works fine.
After that, i want to add this String to anothe big jsonObject to send it to backend with other vars.
jsonObject.put("Tests",myJsonString);
but with this line of code the special character will be escaped and the parser on the backend didnt get it.
How can I avoid it, that myJsonString will be serialized again?
jsonObject.put("Tests",myElement);
doesnt work, because after that there are only references in the jsonObject but no values.
jsonObject.put("Tests", new JSONObject(myJsonString));
(assuming jsonObject is of type org.json.JSONObject)