JSON data list dynamic - android

I am working in Android just for a heads up. I was able to retrieve JSON data but now I have come to the point where there are multiples. Example:
"workers":[
{
"id":3357,
"username":"Unreliable.worker",
"password":"x",
"monitor":0,
"count_all":41,
"count_all_archive":0,
"hashrate":477,
"difficulty":106.56
},
{
"id":4061,
"username":"Unreliable.worker2",
"password":"x",
"monitor":0,
"count_all":0,
"count_all_archive":null,
"hashrate":0,
"difficulty":0
}
would I have to do a for loop or is there another way to do it?
This is the code that I am using now to get them:
JSONObject workersJSONObject = personalJSONObject.getJSONObject("workers");
but I don't know how I would get for each and separate them. I'll get them by using:
id= workersJSONObject.getDouble("id");

[] in JSON refers to a JSON array. You could use something like:
JSONArray workersJSONArray = personalJSONObject.getJSONArray("workers");
Then loop through each item as (basically get each object inside array):
for (int i = 0; i < workersJSONArray.length(); i++) {
JSONObject workersJSONObject = workersJSONArray.getJSONObject(i);
// parse object just like before
}

On JSON, {} defines an object, [] defines an array instead. if you want details. see this and JSONArray
sample:
JSONArray workersJSOnArray = new JSONArray(stringData);
or
JSONArray workersJSOnArray = personalJSONObject.getJSONArray("workers");
/* THen you can loop from each data you want */
int len = workersJSOnArray.length();
for (int i = 0; i < len; i++)
{
JSONObject item = workersJSOnArray.optJSONObject(i);
int id = item.getInt ("id");
.....
}

Related

get JSONArray data inside JSONArray

I need to get "examples" data that is an array inside of 'results'
JSON FILE
and append it to a string. What would be the easiest way to do that?
this is how i would get "definitions"
private JSONObject queryResults;
...
...
String finalResults = "";
JSONArray results = queryResults.getJSONArray("results");
for(int i = 0; i < results.length(); i++){
JSONObject item = results.getJSONObject(i);
finalResults += item.getString("definition") + " ";
}
As this topic is related to Android application, the easiest way to get the mentioned value without using any additional libraries is to check if JSONObject inside the for-loop has attribute definitions and get the value as a String.
You can go with it like this
String finalExamples = "";
JSONArray results = queryResults.getJSONArray("results");
for (int i=0; i < results.length(), i++) {
JSONObject item = results.getJSONObject(i);
if (item.has("examples")) {
examples += item.getString("examples");
}
}
I assumed that you don't want to update your result String value if examples is not available in the JSONObject.
If you want to handle other cases, for example when "examples" is available in the object but is null or is set to empty String you can use other methods of JSONObject to check it.
More info about working with JSONObjects you can find in the documentation

I am trying to parse through a json could some one help me

I excuted the followinf api request
https://api-v3.mbta.com/predictions?sort=arrival_time&filter%5Bstop%5D=70028%2C70029
and I am having the following parsing problem.
Failed to parse JSON
org.json.JSONException: Value [{"attributes":{"arrival_time":"2018-04-25T13:20:01-04:00","departure_time":"2018-04-25T13:20:01-04:00",
"direction_id":1,"schedule_relationship":null,"status":null,"stop_sequence":140,"track":null}
,"id":"prediction-36315805-70029-140","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":
{"data":{"id":"70029","type":"stop"}},"trip":{"data":{"id":"36315805","type":"trip"}}},"type":"prediction"},{"attributes"
:{"arrival_time":"2018-04-25T13:26:03-04:00","departure_time":"2018-04-25T13:26:03-04:00","direction_id":0,"schedule_relationship":null,
"status":null,"stop_sequence":50,"track":null},"id":"prediction-36315802-70028-50","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70028","type":"stop"}},"trip":{"data":{"id":"36315802","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T13:29:28-04:00","departure_time":"2018-04-25T13:29:28-04:00","direction_id":1,"schedule_relationship":null,"status":null,"stop_sequence":140,"track":null},"id":"prediction-36315806-70029-140","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70029","type":"stop"}},"trip":{"data":{"id":"36315806","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T13:33:00-04:00","departure_time":"2018-04-25T13:33:00-04:00","direction_id":0,"schedule_relationship":null,"status":null,"stop_sequence":50,"track":null},"id":"prediction-36315803-70028-50","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70028","type":"stop"}},"trip":{"data":{"id":"36315803","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T13:36:20-04:00","departure_time":"2018-04-25T13:36:20-04:00","direction_id":1,"schedule_relationship":null,"status":null,"stop_sequence":140,"track":null},"id":"prediction-36315807-70029-140","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70029","type":"stop"}},"trip":{"data":{"id":"36315807","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T13:44:44-04:00","departure_time":"2018-04-25T13:44:44-04:00","direction_id":0,"schedule_relationship":"ADDED","status":null,"stop_sequence":50,"track":null},"id":"prediction-ADDED-1524238424-70028-50","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70028","type":"stop"}},"trip":{"data":{"id":"ADDED-1524238424","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T13:52:00-04:00","departure_time":"2018-04-25T13:52:00-04:00","direction_id":1,"schedule_relationship":null,"status":null,"stop_sequence":140,"track":null},"id":"prediction-36315809-70029-140","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70029","type":"stop"}},"trip":{"data":{"id":"36315809","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T13:52:39-04:00","departure_time":"2018-04-25T13:52:39-04:00","direction_id":0,"schedule_relationship":null,"status":null,"stop_sequence":50,"track":null},"id":"prediction-36315757-70028-50","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70028","type":"stop"}},"trip":{"data":{"id":"36315757","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T14:00:20-04:00","departure_time":"2018-04-25T14:00:20-04:00","direction_id":0,"schedule_relationship":null,"status":null,"stop_sequence":50,"track":null},"id":"prediction-36315758-70028-50","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70028","type":"stop"}},"trip":{"data":{"id":"36315758","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T14:09:34-04:00","departure_time":"2018-04-25T14:09:34-04:00","direction_id":1,"schedule_relationship":null,"status":null,"stop_sequence":140,"track":null},"id":"prediction-36315810-70029-140","relationships":{"route":{"data":{"id":"
I am parsing the code like this
private void parseItems(List<GalleryItem> items, JSONObject jsonBody)
throws IOException, JSONException {
JSONObject photosJsonObject = jsonBody.getJSONObject("data");
JSONArray photoJsonArray = photosJsonObject.getJSONArray("attributes");
for (int i = 0; i < photoJsonArray.length(); i++) {
JSONObject photoJsonObject = photoJsonArray.getJSONObject(i);
GalleryItem item = new GalleryItem();
item.setId(photoJsonObject.getString("arrival_time"));
item.setCaption(photoJsonObject.getString("departure_time"));
item.setUrl(photoJsonObject.getString("departure_time"));
items.add(item);
}
}
could some one tell me where I am making a mistake when parsing the object.
thank you
Well, from your posted json data is an array and attributes is an object, you were trying to parse them the other way around. Try this:
JSONArray data = jsonBody.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject singleData = data.getJSONObject(i);
JSONObject attributes = singleData.getJSONObject("attributes");
GalleryItem item = new GalleryItem();
item.setId(attributes.getString("arrival_time"));
item.setCaption(attributes.getString("departure_time"));
item.setUrl(attributes.getString("departure_time"));
items.add(item);
}
As data is a JSONArray, and your photosJsonObject should be JSONArray not object, which contains the objects. Rest is ok I think.

Traverse array IN JSONArray

I'm making an app for android which makes a call to a webservice that returns a json with ARRAY as a parameter, I can go through all the settings and save them easily.
The problem is when I get the array that I returned within the JSON object.
Example of JSON:
[{"codigoArticulo":"0001","nombreArticulo":"CHULETAS DE CORDERO","factorVentasDefecto":"KG","precio":21.95,"factoresDeVenta":["KG","UN"]},{"codigoArticulo":"0007","nombreArticulo":"FALDETA DE CORDERO","factorVentasDefecto":"KG","precio":11.95,"factoresDeVenta":["KG","FL"]}]
I can save "codigoArticulo", "nombreArticulo", "factorVentasDefecto" and "precio easily, BUT i don't know how i can save "factoresDeVenta".
i have this code:
JSONArray resparray = new JSONArray(JSONdevuelto);
for (int i = 0; i < resparray.length(); i++) {
JSONObject respJSON = resparray.getJSONObject(i);
int IDArticulo = respJSON.getInt("codigoArticulo");
String NombreArticulo = respJSON.getString("nombreArticulo");
String FactordeVenta = respJSON.getString("factorVentasDefecto");
int PrecioArticulo = respJSON.getInt("precio");
}
How i can save in one array the variables on "factoresDeVenta"?
I try
String[] Factores = respJSON.getJSONArray("factoresDeVenta");
but no works because are incompatible types.
I need the array to make later a Spinner
Thank you.
factoresDeVenta is an JSONArray inside JSONObject so you will need to use getJSONArray or optJSONArray and use loop for getting values from JSONArray:
JSONArray jArray = respJSON.optJSONArray("factoresDeVenta");
for (int i = 0; i < jArray.length(); i++) {
String str_value=jArray.optString(i); //<< jget value from jArray
}
JSONArray jArray = respJSON.getJSONArray("factoresDeVenta");
It would give you the array of data stored in factoresDeVenta, which you can again traverse to get the individual elements from that array.
You can store in ArrayList<String>
ArrayList<String> arrStr = new ArrayList<String>();
JSONArray jArray = respJSON.optJSONArray("factoresDeVenta");
for (int i = 0; i < jArray.length(); i++) {
arrStr.add(jArray.getString(i));
}
And then you can convert arraylist to string array
String[] Factores = arrStr.toArray(new String[arrStr.size()]);

How to fetch Data From JSON

I have following data from JSON
{
"MenuName": "starter dish",
"SubMenu": [
"pizza dish1",
"pizza dish2"
],
"Price": [
"100",
"110"
]
},
From here i can easily fetch data from "Menuname" key as starter dish but when I fetch data from "Submenu" I get whole string as ["pizza dish1", "pizza dish2"].
Please suggest me way to differentiate both pizza dish1 and pizza dish2
Submenu and Price is not String it is JSONArray so you will need to use for-loop to get all values from Submenu JSONArray as:
JSONArray jsonsubmenu=yourjsonobject.getJSONArray("Submenu");
for(int i=0;i < jsonsubmenu.length();i++){
// get all values from jsonsubmenu JSONArray..
String str_value=jsonsubmenu.optString(i);
....
}
try this
for (int i = 0; i < jsonArray.length(); i++) {
jsonArray.getJSONObject(i).getInt("SubMenu");
}
you can use this link for creating POGO class for your response. It will automatically generate class for your response.
Use google GSON library to parse your response.
or you can simply create a JSON Array or Objects to parse it. in your case it is JSON Object or JSON arrays.
Hi There in that senarerio you have to use
JSONArray _submenu = object.getJSONArray("SubMenu");
for (int i = 0; i < _submenu.length(); i++) {
String text = _submenu.getString(i);
}
JSONArray _price = object.getJSONArray("Price");
for (int i = 0; i < _price.length(); i++) {
String text = _price.getString(i);
}
You can retrieve array values and store it in string[] and use them as per your need. i.e., as follows..
try {
JSONObject jObject = new JSONObject(jsonString);
JSONArray jSubmenu = jObject.getJSONArray("SubMenu");
subMenu = new String[jSubmenu.length()];
for (int i = 0; i < subMenu.length; i++) {
subMenu[i] = jSubmenu.getString(i);
}
JSONArray jPrice = jObject.getJSONArray("Price");
price = new String[jPrice.length()];
for (int i = 0; i < price.length; i++) {
price[i] = jPrice.getString(i);
}
} catch (Exception e) {
// TODO: handle exception
}
Just to throw in a quickie - read up on, and use GSON.
For simple small jobs I find it is the best. Not the fastest running for complex, or long structures, but really quick on the dev side.
Here's the link: google-gson

complex Json Parsing in Android

In my app, i want to parse json response which is in the format
{"quote":[{"orderId":"3209926"},{"totalpages":1}]}
below is the code which i had done,But the problem is how to get the "totalpages" value?
try {
JSONObject jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("quote");
for (int i = 0; i < jArray.length(); i++)
{
JSONObject offerObject = jArray.getJSONObject(i);
current.orderId = offerObject.getInt("orderId");
It shows error when i use
current.totalpage= offerObject.getInt("totalpages");
Anybody knows how to parse this?THanks in advance
Note that getInt(), like other get-functions of JSONObject throw JSONException if the object does not contain the key requested. Thus, before you request the key you should use hasKey() to determine whether the object contains the key.
For example, inside the for loop you can do the following:
JSONObject offerObject = jArray.getJSONObject(i);
if(offerObject.has("orderId") {
current.orderId = offerObject.getInt("orderId");
}
if(offerObject.has("totalpages") {
current.totalpage= offerObject.getInt("totalpages");
}
You can also add a flag and a check after the loop to ensure that both orderId and totalpages were present in the JSON data.
I dont know why your json is having that structure. But if you want to parse it then you will have to do something like the following with the has function.
for (int i = 0; i < jArray.length(); i++) {
JSONObject offerObject = jArray.getJSONObject(i);
if(offerObject.has("orderId")) {
current.orderId = offerObject.getInt("orderId");
} else if(offerObject.has("totalpages")) {
current.totalpage= offerObject.getInt("totalpages");
}
}

Categories

Resources