How to get array number JSON android - android

I have JSON :
{"elements":[{"id":5,"name":"Mathematics","shortName":"math","links":{"courses":[15,30,46,47]}}]}
My code :
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
//Log.d("All Products: ", json.toString());
try {
products = json.getJSONArray("elements");
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
int ids = c.getInt(TAG_PID);
String id = String.valueOf(ids);
if (id.compareTo(id_kh) == 0) {
object = c.getJSONObject("links");
JSONArray courses = object.getJSONArray("courses");///???????????
//result = courses.split("[,]");
Toast.makeText(getBaseContext(),"abc",Toast.LENGTH_LONG).show();
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I dont know to get array number after "courses".

I would use HashMaps. Here you have an example (creating Hashmap from a JSON String
) how to get it from a JSON String.
Particularly for the "courses", once you have been parsed until there, I would use a HashMap<String,List<Integer>>

courses is a JSONArray, so you can do like that:
JSONArray coursesArray = linksObject.getJSONArray("courses");
UPDATE:
To get values from coursesArray :
int value = coursesArray.optInt(position);

Almost there. Once you get your
JSONArray courses = object.getJSONArray("courses");
simply iterate over its values:
// you wanted these numbers in an array
// so let's create one, with size being number of elements in
// JSONArray courses
int[] courseIds = new int[courses.length()];
for (int j=0; j<courses.length(); j++) {
// assign current number to the appropriate element in your array of ints
coursesId[j] = courses.getInt(j);
Log.d("TAG", "number: " + number);
}
The above will save these numbers in an array and print them too:
number: 15
number: 30
number: 46
number: 47
Just keep in mind that "courses" key might not exist, the array might be empty etc.

Related

Why I am getting null JSON response?

I am fetching data from JSON to android.But, I am getting an empty JSON response. The PHP code which generates JSON data is as follows:
$result = $conn->query("SELECT dbname FROM users ORDER BY dbname ASC");
//defined second array for dbnames' list
$dblist = array();
while($row = $result->fetch_assoc()){
//array_push($response['dblist'],$row['dbname']);
$dblist[] = array('name'=>$row['dbname']);
}
$response['dblist'] = $dblist;
This is the JSON response.
{"dblist":[{"name":"a"},{"name":"arsod"}]}
The Java code to fetch data in android is as follows:
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for(int i=0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
institutes.add(name);
}
where institutes is an ArrayList in which I want to add each fetched element. But while fetching the data, I get the error in logcat org.json.JSONException: End of input at character 0 of. What is going wrong?
Considering the following:
s = {"dblist":[{"name":"a"},{"name":"arsod"}]}
Your code should be like,
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for(int i=0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
institutes.add(name);
}
remove this line:
JSONObject object = obj.getJSONObject("dblist");
and replace all occurences of object. with obj.
your JSONObject obj doesn't contain "dblist" object, there is only array inside it, so you should look for getJSONArray("dblist") straight inside obj
edit: you are parsing different String s, I've just checked this code:
final String s = "{\"dblist\":[{\"name\":\"a\"},{\"name\":\"arsod\"}]}";
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for (int i = 0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
which is almost exacly same as your and works pretty fine...

How can I put JSON return in an array?

I'm a android beginner and I'm doing to access a JSON file in and it has an error. I have a problem in parsing this
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray accounts = jsonObject.getJSONArray("account_data");
for(int i=0;i < accounts.length();i++){
JSONObject a = accounts.getJSONObject(i);
sin = a.getString("sin");
account_name = a.getString("account_name");
address = a.getString("address");
status = a.getString("status");
due_date = a.getString("due_date");
total_amount = a.getDouble("total_amount");
sin_lbl.setText(a.getString("account_name"));
}
here is the JSON File
{"account_data":{
"sin":"200111-102 ",
"account_name":"LUMABAN, CRISTOM ",
"address":"352 MABINI ST.,, SABANG, Baliwag ",
"status":"A ",
"due_date":"2019-04-23",
"total_amount":"491.00"
},"code":1101,"message":"Account Info Retrieved"}
I have an error in putting it in array.
Instead of using JSONArray , try to use JSONObject.
String[] array = {json.get("sin"), json.get("account_name"), json.get("address"), json.get("status"), json.get("due_date"), json.get("total_amount") }
{"account_data":{"sin":"200111-102 ","account_name":"LUMABAN, CRISTOM ","address":"352 MABINI ST.,, SABANG, Baliwag ","status":"A ","due_date":"2019-04-23","total_amount":"491.00"},"code":1101,"message":"Account Info Retrieved"}
Actually, it's a json object, not array. So that you can not convert json object to json array
Difference between Json Array and Json Object:
A JSONArray is an ordered sequence of values. A JSONObject is an unordered collection of name/value pairs.
JSONArray: Its external text form is a string wrapped in square brackets with commas separating the values.
JSONObject: Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names.
Please use this json parshing
try {
JSONObject jsonObject = new JSONObject(jsonStr);
JSONObject accounts = jsonObject.getJSONObject("account_data");
sin = accounts.getString("sin");
account_name = accounts.getString("account_name");
address = accounts.getString("address");
status = accounts.getString("status");
due_date = accounts.getString("due_date");
total_amount = accounts.getDouble("total_amount");
sin_lbl.setText(a.getString("account_name"));
} catch (Exception e) {
}
if you asked about iterating on json object you could try this one
JSONObject jObject = new JSONObject(jsonStr);
JSONObject menu = jObject.getJSONObject("account_data");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = menu.getString(key);
map.put(key,value);
}
so now you have your data into as pair of key and value
if you have a json array of this response you could do as following
JSONObject root = new JSONObject("your root");
JSONArray resultArray = root.getJSONArray("your array key");
for (int i = 0; i < resultArray.length(); i++) {
// here to get json object one by one and access every item into it
JSONObject resultObject = resultArray.getJSONObject(i);
posterPath = resultObject.getString("key");
title = resultObject.getString("key");
releaseDate = resultObject.getString("key");
description = resultObject.getString("key");
voteAverage = resultObject.getDouble("key");
}

I want to parse this JSON with volley but I am not able to do it

I want to parse this JSON in Volley Library. I have set everything I want to parse name of the recipe and image. Problem is that I want three recipes to be parsed at same time but here it have same Object name Recipe and I don't know how to parse same object name for three different TextViews.
Here is the JSON format: link
Here is the code I tried but it gave me one name not three different names:
try {
JSONArray list = response.getJSONArray("hits");
Log.v ("MISH", "List: " + list);
for (int x = 0; x<list.length(); x++) {
JSONObject obj = list.getJSONObject(x);
JSONObject main = obj.getJSONObject("recipe");
String label = main.getString("label");
String image = main.getString("image");
Picasso.with(getApplicationContext()).load(image).into(recipeOne);
Log.v("FISH", "NAME FATCH: " + label);
recipeOneText.setText(label);
}
Try this.
And use optString in your code:
try {
if (TextUtils.isEmpty(response)) {
Toast.makeText(this, "response is null", Toast.LENGTH_SHORT).show();
return;
}
JSONObject jsonObject = new JSONObject(response);
JSONArray hits = jsonObject.getJSONArray("hits");
// edited here ,add data in your code
JSONObject jo1 = hits.getJSONObject(0);
hits.put(0,jo1); // add jo1 JSONObject to the JSON array, the angle is 0
hits.put(1,jo1); // add jo1 JSONObject to the JSON array, the angle is 1
hits.put(2,jo1); // add jo1 JSONObject to the JSON array, the angle is 2
for (int i = 0; i < hits.length(); i++) {
JSONObject jo = hits.getJSONObject(i);
JSONObject recipe = jo.getJSONObject("recipe");
String label = recipe.optString("label");
String image = recipe.optString("image");
Picasso.with(getApplicationContext()).load(image).into(recipeOne);
Log.v("FISH", "NAME FATCH: " + label);
recipeOneText.setText(label);
}
} catch (JSONException e) {
e.printStackTrace();
}
Edit
// If your don't have to much data in your code , you can do like this .
JSONObject jo1 = hits.getJSONObject(0);
hits.put(0,jo1); // add jo1 JSONObject to the JSON array, the angle is 0
hits.put(1,jo1); // add jo1 JSONObject to the JSON array, the angle is 1
hits.put(2,jo1); // add jo1 JSONObject to the JSON array, the angle is 2

data from a jsonobject in android

The below is called from a string url and returns a json object which has an json array inside, but something else is not working, can anyone show me how to access the data inside?
{"data":[{"8196":{"booking_id":"8150","client_id":"107","venue_id":null}}]
String jsonStr = "{\"data\":[{\"8196\":{\"booking_id\": \"8150\",\"client_id\": \"107\",\"venue_id\": null}}]}";
try {
JSONObject json = new JSONObject(jsonStr);
JSONArray array = json.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
Iterator it = o.keys();
while (it.hasNext()) {
String name = (String) it.next();
o = o.getJSONObject(name);
int bookingId = o.getInt("booking_id");
int clientId = o.getInt("client_id");
int venueId = o.optInt("venue_id");
Log.v("TEST", String.format("Booking ID: %s -- Client ID: %s -- Venue ID: %s", bookingId, clientId, venueId));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I guess this is what you'll want. By the way, the JSON you posted is malformed. It's missing a } in the end.
You first need to decode the JSON string. The JSON sting you got in return is actually a serialized version of a JSON object.
You need to decode that string into a native Java Object.
There are a number of methods to this in Java. You can start by checking out the Java section at json.org.
I think the problem is that the value of key venue_id is null. You can replace null value with empty string(""), try it.

Android: Decoding JSON

[{"placeID":"p0001","placeName":"INTI International University","placeType":"Education","placeLat":"2.813997","placeLng":"101.758229","placePict":""},{"placeID":"p0002","placeName":"Nilai International College","placeType":"Education","placeLat":"2.814179","placeLng":"101.7700107","placePict":""}]
How do I decode the JSON sent from my PHP script on Android?
please try this
String s = "[{\"placeID\":\"p0001\",\"placeName\":\"INTI International University\",\"placeType\":\"Education\","
+ "\"placeLat\":\"2.813997\",\"placeLng\":\"101.758229\",\"placePict\":\"\"},"
+ "{\"placeID\":\"p0002\",\"placeName\":\"Nilai International College\",\"placeType\":\"Education\",\"placeLat\":\"2.814179\",\"placeLng\":\"101.7700107\",\"placePict\":\"\"}]";
ArrayList<String> arrplaceID = new ArrayList<String>();
ArrayList<String> arrplaceName = new ArrayList<String>();
try {
JSONArray arr = new JSONArray(s);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonObject = arr.getJSONObject(i);
arrplaceID.add(jsonObject.optString("placeID"));
arrplaceName.add(jsonObject.optString("placeName"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < arrplaceID.size(); i++) {
Log.e("arr[" + i + "] place Name", arrplaceName.get(i));
}
What is the problem in this Please Read this tutorial for parsing JSON it might be helpful in future also.json parsing link
Follow below points.
1) it seems the response you are getting is Json Array. so create one json array by response string.
JSonArray jArray = new JsonArray(responseString);
2) now you have your response in jArray. now iterate a loop and take json object from JsonArray, in your case you have two json objects.
for(i,i<jArray.size,i++)
{
JsonObject obj=jArray.get(i);
// here you got your first entry in jsonObject.
// nor use this obj according to ur need. you can say obj.getString("placeID");
// and so on.
}
refer this to understand more on json link
use JSONArray class:
JSONArray jsonplaces = new JSONObject(stringPlaces);
then your able to iterate throught array by using for-loop:
for (int i = 0; i < jsonplaces.length(); i++) {
JSONObject jsonplace = (JSONObject) jsonplaces.get(i);
//read items, for example:
String placeName = jsonplace.getString("placeName");
}

Categories

Resources