String cannot be converted to JSONArray Android - android

I am trying to extract the long url from Google URL api. Following is code snippet, I am trying to get on with:
` StringBuilder url = new StringBuilder(URL);
url.append(shortUrl);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject jsonObj = new JSONObject(data);
JSONArray ja = jsonObj.getJSONArray("longUrl");
JSONObject last = ja.getJSONObject(0);
return last;
The function containing code returns a JSON object. In logcat, I am seeing an error org.json.JSONException: Value http://www.google.com/ at longUrl of type java.lang.String cannot be converted to JSONArray
The code is receiving the full url (http://www.google.com) but I am doing something wrong with JSONArray.

Try jsonObj.getString("longUrl") instead of jsonObj.getJSONArray("longUrl"), because "longUrl" is a String not an Array and of course, assign the result in a String instead of a JSONArray.

Related

Json Parsing in Android with multiple same rows

Well,it is simple yet I am finding confused to extract the info.Could you give a look here:
formatted JSON Data
[
{
"catalogName":"a",
"categoryName":"aa",
"subCategoryName":"aaa",
"price":888.0,
},
{
"catalogName":"b",
"categoryName":"bb",
"subCategoryName":"bbb",
"productName":"hjb",
"price":9.0,
}
]
I would be printing this in my android app.Thanks
Here is how I do in my code:
HttpGet httpGet = new HttpGet(uri);
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("Content-type", "application/json");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
StatusLine statusLine = httpResponse.getStatusLine();
// Check StatusLine result ....
// Convert response to a JSon Array:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
httpResponse.getEntity().writeTo(baos);
baos.close();
JSONArray jsonArray = new JSONArray(baos.toString())
for(int i = 0; i < jsonArray.length(); ++i)
{
// Extract values from JSON row:
JSONObject jsonObject = jsonArray.getJSONObject(i);
String catalogName = jsonObject.has("catalogName") ? jsonObject.getString("catalogName") : "";
String categoryName = jsonObject.has("categoryName") ? jsonObject.getString("categoryName") : "";
String subCategoryName = jsonObject.has("subCategoryName") ? jsonObject.getString("subCategoryName") : "";
String productName = jsonObject.has("productName") ? jsonObject.getString("productName") : "";
double price = jsonObject.has("price") ? jsonObject.getString("price") : 0.;
// Do stuff with data:
...
}
Please note that if a row misses a value (like productName) you must handle it. In the example I assign a default value but maybe it's not the best choice.
JSONArray jsonArray=new JSONArray("YOUR_JSON_ARRAY_NAME"); //Must be case sensitive
for(int i=0;i<jsonArray.length();i++){
JSONObject current_job= jsonArray.getJSONObject(i);
String catalogName= current_job.getString("catalogName");
//same for other fields. KEY must be case sensitive
...
...
}
This is a JSONArray :-) Parse it with this:
String json = /** your JSON **/
JSONArray array = new JSONArray(json);
And now you can take the data out of the object with getJSONObject(int index) :-)
I suggest using a JSON parsing library, such as Gson. It is fast and very simple to use.
https://github.com/google/gson
If you have a following class:
class Catalog{
private String catalogName;
private String categoryName;
private String subCategoryName;
private String productName;
private double price;
/** Getter, setters, optional: toString, constructor... **/
}
To parse it simply call:
Type listType = new TypeToken<List<Catalog>>() {}.getType();
List<Catalog> yourList = new Gson().fromJson(YOUR_JSON_STRING, listType);
Instead of this "confusing" code for listType you can use also Class (see documentation), but this is not possible in your case, as provided JSON format is a direct list of elements, it is not wrapped. For using a class you would have to wrap this JSON with another element.

How to parse a specific response of a RESTful WS using JSON

I am learning how to parse a response from a restful web service It is supposed to retreive a JSON string so I can parse it, I am using the apache libs in android. Following some questions here in StackOverflow I do the following:
HttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(URL);
ResponseHandler<String> handler = new BasicResponseHandler();
try{
result = httpClient.execute(request, handler); ...
with that I can retreive the result of the WS as this:
"[{\"CodigoRTA\":\"0\",\"MensajeRTA\":\"\",\"Respuesta\":\"[{\\"codigo\\":\\"05\\",\\"nombre\\":\\"ANTIOQUIA\\"},{\\"codigo\\":\\"76\\",\\"nombre\\":\\"VALLE DEL CAUCA\\"}]\"}]"
the thing is that I am trying to parse it with JSONObject and JSONArray without success; When I try to use the JSONObject the errorhandler says that it cannot convert the string into JSONObject, so I look up for an answer or a similar problem and found that if the result starts with [] square brackets represents starting of an JSONArray node and curly bracket {} represents JSONObject, so I try to use this code:
//JSONObject jsonObject = new JSONObject(result);
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
codeDepartment[i] = json_data.getInt("codigo");
NameDepartment[i] = json_data.getString("nombre");
}
without success either, it now says that "it cannot convert String into JSONArray. So any idea of what can I use? any help would be really appreciated.
Well, it seems that the server response is similar to Json response, the thing is all of the \ that it contains. One thing you could do is to replace or remove 1 of the \ backslash and then try to asign the new value to the JSONArray. Something like this:
result = httpClient.execute(request, handler);
result = result.replace("here the info you want to replace", "here with new values to replace with ");
JSONArray jArray = new JSONArray(result);
hope it help you.

How to Parse from the JSON file? [duplicate]

This question already has answers here:
Sending and Parsing JSON Objects in Android [closed]
(11 answers)
Closed 9 years ago.
I have following objects in JSON file. I have to parse it and store it in a file. What will be the android code for doing this?
{
"result":"ok",
"numbers":
[
{
"First":"first",
"Second":"second",
"Third":"third",
"Fourth":"fourth",
"Fifth":"fifth"
}
]
}
Any one find me getting out of this? I would really appreciate your work.
{ -> json object
"result":"ok",
"numbers":[-> json array
{
Do like this
JSONObject jobject=new JSONObject(jsonString);
JSONArray jarray=Jobject.getJSONArray("numbers");
String result=jobject.getJSONObject("result");
for(int i=0;jarray.length();i++){
String first= jarray.getJSONObject(i).getString("First");
String Second= jarray.getJSONObject(i).getString("Second");
}
{ // json object node
"result":"ok",
"numbers":[// json array numbers
{
"First":"first",
To parse
JSONObject jb = new JSONObject("your json");
String result = (JSONArray)jb.getString("result");
JSONArray jr = (JSONArray)jb.getJSONArray("numbers");
JSONObject jb1= (JSONObject) jr.getJSONObject(0);
String first = jb1.getString("First");
// similarly for second third and fourth
Once you parse you can write the result to a file.
Edit:
Note: Network operation must be done in a background thread. Use Asynctask
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("your json url ");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
}catch(Exception e)
{
e.printStackTrace();
}
Now use _response JSONObject jb = new JSONObject("_response);. Rest all is the same
Try Using the following
import org.json.JSONArray;
import org.json.JSONObject;
JSONObject json = null;
JSONArray jsonArray = null;
String data = null;
json = new JSONObject(response);
data = json.getString("numbers");
jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
String str =jsonArray.getJSONObject(i).toString();
}
always remember { means object and [ means array so you can proceed with following code in the give
JSONObject firstjobject=new JSONObject(jsonString);
JSONArray firstjarray=firstjobject.getJSONArray("numbers");
String result=firstjobject.getJSONObject("result");
for(int i=0;firstjarray.length();i++){
String first= firstjarray.getJSONObject(i).getString("First");
String Second= firstjarray.getJSONObject(i).getString("Second");
}
here numbers is an array and First,Second etc are the keys for relative data values

java.lang.Long cannot be converted to JSONArray

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://gateway.ceylonlinux.com/hayleys2/services/getUserStokDetail?token=40da9b9ed74f672c3871d76a2c87857b&timestamp=0");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(httpPost, responseHandler);
JSONObject posts = new JSONObject(responseBody);
JSONArray jArray = posts.getJSONArray("timestamp");
Log.i("Tag", jArray.toString());
I tried above code to retrieve data from server but when i try that i get following error
12-06 11:12:27.539: W/System.err(4870): org.json.JSONException: Value 1386308549000 at timestamp of type java.lang.Long cannot be converted to JSONArray
timestamp is value instead of JSONArray.stock is JSONArray. get both value as:
JSONArray jArray = posts.getJSONArray("stock"); /// get stock JSONArray
Log.i("Tag", jArray.toString());
long timestamp=posts.getLong("timestamp"); /// get timestamp
Replace this line
JSONArray jArray = posts.getJSONArray("timestamp");
With this one :
long mTimeStamp = posts.getLong("timestamp");
Because in your JSON String timestamp is an long value not an array
In your JSON String stock is an array so you can get stock by using this
JSONArray jArray = posts.getJSONArray("stock");
check your Json string whether it has jsonArray named timestamp or it have only a long variable named timestamp. you can check this link for json structure also.

android:json parsing to decode

I am making an app in which i am getting a string as response from server side. that response is encoded in json. Now my problem is How to do json parsing of the encoded response from server side to decode it..
I am geting the following response from server
["ekjyot#emobx.com","prince6179#gmail.com","facebook_514728069"]
It is in the form of an array.I want to decde it and display as textviws in my another activity.
I am using the following code:
HttpClient client = new DefaultHttpClient();
String getURL = "http://www.ondamove.it/English/mob/profile_friends.php?email="+Login.eMailId+"";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null)
{
String s = EntityUtils.toString(resEntityGet);
System.out.println(s);
JSONArray ids = new JSONArray(s);
for(int i=0; i< ids.length(); i++){
System.out.println(ids[]); //print each of the string in json array.
}
but it is giving me the error :
The type of the expression must be an array type but it resolved to JSONArray
how to resolve this issue.
can anyone help me over this?
thanks
You can use JSONTokener to parse JSON documents for example:
String json = "{"
+ " \"query\": \"Pizza\", "
+ " \"locations\": [ 94043, 90210 ] "
+ "}";
JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
String query = object.getString("query");
JSONArray locations = object.getJSONArray("locations");
get your response as string
String jsonResponseString = Sever.getResponse();
JSONArray ids = new JSONArray(jsonResponseString);
for(int i=0; i< ids.length(); i++){
Log.i(TAG, ids[i]); //print each of the string in json array.
}
GSON if you just want to keep it simple. Jackson streaming if you need raw speed.
Or you could always use the built in JSON tools -- but I'd recommend one of these other two.

Categories

Resources