Hi I am using json parsing, I am getting json response from backend and parsing is working well. but the issue is that when I try to set data as per response it sets last index only. Following is my snippet code and json response can any one help me with this please.
Right now it shows output
(in my first textview)
Buy 12 Canex + 1 Dose Free
(in my second textview)
Buy 12 Canex + 1 Dose Free
{
"Data": {
"shippingText": "heyy",
"productOffersList": [
{
"bgColorA": "#ffffff",
"bgColorI": "255*255*255",
"offerLine": [
{
"text": "BUY 6",
"colorA": "#82d7ff",
"colorI": "130*215*255"
},
{
"text": " Canex + 1 Dose Free",
"colorA": "#ff8282",
"colorI": "255*130*130"
}
]
},
{
"bgColorA": "#ffffff",
"bgColorI": "255*255*255",
"offerLine": [
{
"text": "BUY 12",
"colorA": "#65dd63",
"colorI": "101*221*99"
},
{
"text": " Canex + 1 Dose Free",
"colorA": "#ff8282",
"colorI": "255*130*130"
}
]
}
]
},
"Status": 1,
"Message": "",
"UserMessage": ""
}
Code
JSONArray productOffersList=drawerdatas.getJSONArray("productOffersList");
for(int k=0;k<productOffersList.length();k++)
{
JSONObject joofer = productOffersList.getJSONObject(k);
JSONArray offerLine=joofer.getJSONArray("offerLine");
offertextlist=new ArrayList<ProductOffersModel>();
for(int l=0;l<offerLine.length();l++)
{
JSONObject jooferline = offerLine.getJSONObject(l);
ProductOffersModel pom=new ProductOffersModel();
pom.setProductOffers_text(jooferline.getString("text"));
pom.setProductOffers_colorA(jooferline.getString("colorA"));
offertextlist.add(pom);
}
}
for(int v=0;v<offertextlist.size();v++)
{
product_view_offertextfirst.setText(offertextlist.get(v).getProductOffers_text()+" "+offertextlist.get(v).getProductOffers_text());
}
for(int v=0;v<offertextlist.size();v++)
{
product_view_offertexttwo.setText(offertextlist.get(v).getProductOffers_text()+" "+offertextlist.get(v).getProductOffers_text());
}
because you are doing a for loop to set the text of the textviews you are setting on both all the offers and the last one is what you are able to see
JSONArray productOffersList=drawerdatas.getJSONArray("productOffersList");
offertextlist=new ArrayList<ProductOffersModel>();
// You were re creating the list array list inside the for loop so you were losing the data from the 1st product.
for(int k=0;k<productOffersList.length();k++)
{
JSONObject joofer = productOffersList.getJSONObject(k);
JSONArray offerLine=joofer.getJSONArray("offerLine");
for(int l=0;l<offerLine.length();l++)
{
JSONObject jooferline = offerLine.getJSONObject(l);
ProductOffersModel pom=new ProductOffersModel();
pom.setProductOffers_text(jooferline.getString("text"));
pom.setProductOffers_colorA(jooferline.getString("colorA"));
offertextlist.add(pom);
}
}
if(offertextlist !=null && offertextlist.size()==4)
{
product_view_offertextfirst.setText(offertextlist.get(0).getProductOffers_text()
+ " " + offertextlist.get(1).getProductOffers_text());
product_view_offertexttwo.setText(offertextlist.get(2).getProductOffers_text()
+ " " + offertextlist.get(3).getProductOffers_text());
}
try with this parsing,
JSONArray productOffersList=drawerdatas.getJSONArray("productOffersList");
for(int k=0;k<productOffersList.length();k++)
{
JSONObject joofer = productOffersList.getJSONObject(k);
JSONArray offerLine=joofer.getJSONArray("offerLine");
offertextlist=new ArrayList<ProductOffersModel>();
ProductOffersModel pom=new ProductOffersModel();
pom.setProductOffers_text
(offerLine.getJSONObject(0).getString("text")+""+
offerLine.getJSONObject(1).getString("text"));
offertextlist.add(pom);
}
for(int v=0;v<offertextlist.size();v++)
{
if(v==0)
{
product_view_offertextfirst.setText
(offertextlist.get(v).getProductOffers_text());
}
else if(v==1)
{
product_view_offertexttwo.setText(
offertextlist.get(v).getProductOffers_text());
}
}
Handling JSON data manually is not a recommended practice for large datasets. You should go with a JSON parsing library, Gson may be a good choice.
https://github.com/google/gson
Related
{
"items": [
{
"volumeInfo": {
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "0080509576"
},
{
"type": "ISBN_13",
"identifier": "9780080509570"
}
]
}
}
]
}
In the above json, I need to extract industryIdentifiers' identifier value without losing any digit.
I have tried using JSONArray but it eats up some of the digits
jsonObj.getJSONObject("items")
.getJSONObject("volumeInfo").getJSONArray("industryIdentifiers")
.getString(0);
Can anyone help me out?
Get the json array first and then iterate through it to parse.
Use org.json
import org.json.JSONArray;
import org.json.JSONObject;
JSONArray array = jsonObj.getJSONArray("items").getJSONObject(0).getJSONObject("volumeInfo")
.getJSONArray("industryIdentifiers");
for (int i = 0; i < array.length(); i++) {
String type = array.getJSONObject(i).getString("type");
String identifier = array.getJSONObject(i).getString("identifier");
System.out.println(type + " identifier : " + identifier);
}
Output on Java 9
ISBN_10 identifier : 0080509576
ISBN_13 identifier : 9780080509570
I am an aspiring Android developer. I don't have a lot of experience in creating applications yet.
I have an API, and the code to call and retrieve the data. The issue I am having is it is only pulling the first record. When I run the debug tool I can see that it finds all three, but it is only printing the first one. Any help and guidance is very much appreciated.
Here is my code:
JSONObject parentObject = new JSONObject(finalJson);
JSONObject reportObject = parentObject.getJSONObject("report");
String mReport = reportObject.getString("foods");
JSONArray foodArray = reportObject.getJSONArray("foods");
JSONObject mFood = foodArray.getJSONObject(0);
String foodName = mFood.getString("name");
String foodMeasure = mFood.getString("measure");
JSONArray nutrientsArray = mFood.getJSONArray("nutrients");
for(int i = 0; i < nutrientsArray.length(); ++i) {
JSONObject nutrientObject = nutrientsArray.getJSONObject(i);
String nutrientName = nutrientObject.getString("nutrient");
String nutrientValue = nutrientObject.getString("value");
return foodName + "\nNutrient: " + nutrientName + "\nMeasure: " + foodMeasure + "\nValue: " + nutrientValue;
}
Here is the API data:
API database link
{
"report": {
"sr": "Legacy",
"groups": "All groups",
"subset": "All foods",
"end": 150,
"start": 0,
"total": 7524,
"foods": [
{
"ndbno": "09427",
"name": "Abiyuch, raw",
"weight": 114,
"measure": "0.5 cup",
"nutrients": [
{
"nutrient_id": "203",
"nutrient": "Protein",
"unit": "g",
"value": "1.71",
"gm": 1.5
},
{
"nutrient_id": "204",
"nutrient": "Total lipid (fat)",
"unit": "g",
"value": "0.11",
"gm": 0.1
},
{
"nutrient_id": "205",
"nutrient": "Carbohydrate, by difference",
"unit": "g",
"value": "20.06",
"gm": 17.6
}
]
},
And here are my results(they are being parsed correctly)
foodName:"Abiych, raw" nutrientName: "Protein" foodMeasure: "0.5 cup" nutrientValue: "1.74"
How do I get it to pull and display the other two items from the API that are called?
Thank you so much!
Your for loop has a return statement. It quits for loop and the method after first iteration. Store results in an array and return the array out of the for loop.
I was able to solve it using this. The for loop execution answer is what helped me see my error. Thank you!
StringBuffer finalBufferedData = new StringBuffer();
for(int i = 0; i < nutrientsArray.length(); ++i) {
JSONObject nutrientObject = nutrientsArray.getJSONObject(i);
String nutrientName = nutrientObject.getString("nutrient");
String nutrientValue = nutrientObject.getString("value");
finalBufferedData.append( "\nNutrient: " + nutrientName +
"\nMeasure: " + foodMeasure + "\nValue: " + nutrientValue +"\n "+"\n ");
}
return foodName + "\n" + finalBufferedData.toString();
I am thinking of a new way to extract data from JSON. The following example is what I want:
Look for a key and value pair and give me that object.
Inside that object, give me the value to this key.
I want to get the power of knighthero in the following JSON, by telling it to find the username knighthero. This is really difficult, and I've tried JSONArray and JSONObject, but can't figure it out. I know the length is 3, but now what?
{
"data": [
{
"power": 75,
"registrant": {
"group": "elf",
"username": "kevin23"
}
},
{
"power": 34,
"registrant": {
"group": "fairy",
"username": "msi56"
}
},
{
"power": 150,
"registrant": {
"group": "orc",
"username": "knighthero"
}
}
]
}
I have tried JsonPath and all I get is [] when I print the string. I have tried JSONArray, but can't figure out how to do it.
With org.json librairy and your json described.
JSONObject jo0 = new JSONObject("{\"data\": ["
+ "{\"power\": 75,"
+ "\"registrant\": {\"group\": \"elf\",\"username\": \"kevin23\"}},"
+ "{\"power\": 34,"
+ "\"registrant\": {\"group\": \"fairy\",\"username\": \"msi56\"}},"
+ "{\"power\": 150,"
+ "\"registrant\": {\"group\": \"orc\",\"username\": \"knighthero\"}}"
+ "]}");
JSONArray ja = jo0.getJSONArray("data");
for(int i=0;i<ja.length();i++){
if(ja.getJSONObject(i).getJSONObject("registrant").getString("username").equals("knighthero")){
System.out.println(ja.getJSONObject(i).getInt("power"));
break;
}
}
EDIT
My bad, I make a mistake, here the good version
I have a json link, if we open it I get a following result
{
"Status": "Success",
"All_Details": [{
"Types": "0",
"TotalPoints": "0",
"ExpiringToday": 0
}],
"First": [{
"id": "0",
"ImagePath": "http://first.example.png"
}],
"Second": [{
"id": "2",
"ImagePath": "http://second.example.png"
}],
"Third": [{
"id": "3",
"ImagePath": "http://third.example.png"
}],
}
What I need is, I want to dynamically get all the key names like status, All_details, First etc.
And I also want to get the data inside the All_details and First Array.
I used following method
#Override
public void onResponse(JSONObject response) throws JSONException {
VolleyLog.d(TAG, "Home Central OnResponse: " + response);
String statusStr = response.getString("Status");
Log.d(TAG, "Status: " + statusStr);
if (statusStr.equalsIgnoreCase("Success")) {
Iterator iterator = response.keys();
while (iterator.hasNext()) {
String key = (String)iterator.next();
}
}
}
I get all the key names in get stored in the String key. But I am unable to open get the values inside the JSON array, for eg. I need to get the values inside first and second array using the String(Key). How can I do that.???
First, to get the keynames, you can easily iterate through the JSONObject itself as mentioned here:
Iterator<?> keys = response.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( response.get(key) instanceof JSONObject ) {
System.out.println(key); // do whatever you want with it
}
}
Then, to get the values of the array:
JSONArray arr = response.getJSONArray(key);
JSONObject element;
for(int i = 0; i < arr.length(); i++){
element = arr.getJSONObject(i); // which for example will be Types,TotalPoints,ExpiringToday in the case of the first array(All_Details)
}
If you want to get the JSON array from the response JSONObject you can use the JSONArray class. JSONObject has a method to get a JSONArray: getJSONArray(String). Remember to catch the JSONException when trying this. This exception will be thrown if there is no key for example.
Your code could look like this (only the while loop):
while (iterator.hasNext()) {
String key = (String)iterator.next();
try {
JSONArray array = response.getJSONArray(key);
// do some stuff with the array content
} catch(JSONException e) {
// handle the exception.
}
}
You can get the values from the array with the methods of JSONArray (see the documentation)
Something like this will allow you to iterate on array and individual fields once you have extracted the keys using what you have done. Instead of "Types" use the key variable you will create before this.
JSONArray allDetails = response.getJsonArray("All_Details")
for (int i = 0 ; i < allDetails.length(); i++) {
JSONObject allDetail = allDetails.getJSONObject(i);
allDetails.getString("Types");
}
First of all I want to inform you that it's not a valid JSON. Remove the last Comma (,) to make it valid.
Then you can Iterate like here
JSONArray myKeys = response.names();
Try this one
Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
try {
String dynamicKey = (String) keys.next();//Your dynamic key
JSONObject item = jsonObject.getJSONObject(dynamicKey);//Your json object for that dynamic key
} catch (JSONException e) {
e.printStackTrace();
}
}
New to Android and Java in general and I'm learning how to make a JSON call. To do so, I'm following this guide: http://mobiforge.com/design-development/consuming-json-services-android-apps
Here's where things get confusing for me. The author of that tutorial wants the reader to call this API: http://ws.geonames.org/findNearByWeatherJSON?lat=37lng=122
Which returns a JSON object in this format:
{
"weatherObservation": {
"clouds":"scattered clouds",
"weatherCondition":"n/a",
"observation":"KCFV 090852Z AUTO 06005KT
10SM SCT090 SCT110 24/20 A3000 RMK AO2
SLP148 T02390200 53002",
"windDirection":60,
"ICAO":"KCFV",
"seaLevelPressure":1014.8,
"elevation":225,
"countryCode":"US",
"lng":-95.56666666666666,
"temperature":"23.9",
"dewPoint":"20",
"windSpeed":"05",
"humidity":78,
"stationName":"Coffeyville, Coffeyville
Municipal Airport",
"datetime":"2012-07-09 08:52:00",
"lat":37.083333333333336
}
}
Pretty straight forward, except that the API is no longer valid/has limits. In order to finish the project I've instead opted to call this API: http://api.openweathermap.org/data/2.5/weather?lat=37.77&lon=-122.419
Which returns the JSON in this format
{
"coord": {
"lon": 139,
"lat": 35
},
"sys": {
"country": "JP",
"sunrise": 1369769524,
"sunset": 1369821049
},
"weather": [
{
"id": 804,
"main": "clouds",
"description": "overcast clouds",
"icon": "04n"
}
],
"main": {
"temp": 289.5,
"humidity": 89,
"pressure": 1013,
"temp_min": 287.04,
"temp_max": 292.04
},
"wind": {
"speed": 7.31,
"deg": 187.002
},
"rain": {
"3h": 0
},
"clouds": {
"all": 92
},
"dt": 1369824698,
"id": 1851632,
"name": "Shuzenji",
"cod": 200
}
I can make the call just fine, but how do I display the "main" and "description" strings in the "weather" array? More specifically, how do I display this information as a Toast?
Here's what I have:
protected void onPostExecute(String result){
try {
JSONArray weatherArray = new JSONArray(result);
JSONArray wArray = new JSONArray("weather");
String mainWeather = wArray.getString(1);
String mainDescription = wArray.getString(2);
Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
BecauseI am following the mobiforge Tutorial, I have not deviated anywhere else except for this particular block of code.
Thanks for the help!
Edit:
There are several solutions here that work see #swats and #user3515851. I have chosen #remees-m-syde due to it's simplicity. Primarily because his solution did not require that I go through the for loop.
I have used optJSONArray or optString, instead of getJSONArray or getString as "opt" will return "" if there is no value for that key.. it will not throw any exception like in case of getString()
Try below code
JSONObject rootJsonObj = new JSONObject(result);
JSONArray wArray = rootJsonObj.optJSONArray("weather");
for (int i = 0; i < wArray.length(); i++) {
JSONObject weatherJsonObj = wArray.optJSONObject(i);
String mainWeather = weatherJsonObj.optString("main");
String mainDescription = weatherJsonObj.optString("description");
Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();
}
Parsing issue was there, You should have taken object from response result.
EDIT: No need of try catch block while using optJSONArray or optString.
You are unable to get the data because there is one json object inside the "weather" JSONArray.
JSONArray starts with - [
JSONObject starts with - {,
So first get the JSONArray and then the JSONObject inside it.
"weather": [ ----Array
{ ----Object
"id": 804,
"main": "clouds",
"description": "overcast clouds",
"icon": "04n"
}
]
You have to get this JSONObject and then get the String from it like the below code showing.
JSONObject weatherArray = new JSONObject(result);
JSONArray wArray = weatherArray.getJSONArray("weather");
JSONObject jobj = wArray.getJSONObject(0);
String mainWeather = jobj.getString("main");
String mainDescription = jobj.getString("description");
Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();
When there is multiple object in Array, Get it as below.
JSONObject rootJsonObj = new JSONObject(result);
JSONArray wArray = rootJsonObj.optJSONArray("weather");
for (int i = 0; i < wArray.length(); i++) {
JSONObject weatherJsonObj = wArray.getJSONObject(i);
String mainWeather = weatherJsonObj.getString("main");
String mainDescription = weatherJsonObj.getString("description");
Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();
}
protected void onPostExecute(String result){
try {
JSONObject weatherArray = new JSONObject(result);
JSONArray wArray = weatherArray.getJSONArray("weather");
for(int i=0;i<wArray.length,i++){
JSONObject object=wArray.getJSONObject(i);
String mainWeather=object.getString("main");
String mainDescription=object.getString("description");
Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
I hope this one will help to you :)
I assume you obtained the weather array from parsing this JSON now to retrieve the values from it
JSONObject object=null;
try {
JSONObject object=array.getJSONObject(0);
String main=object.getString("main");
String description=object.getString("description");
} catch (JSONException e) {
e.printStackTrace();
}
and now use the strings in your toast
Assuming result contains the JSON, here is how to get main, and description form weather :
JSONObject resJSON = new JSONObject(result);
JSONArray weatherArray = resJSON.getJSONArray("weather");
for(int i = 0; i < weatherArray.length(); i++) {
JSONObject weatherJSON = weatherArray.getJSONObject(i);
System.out.println(weatherJSON.getString("main"));
System.out.println(weatherJSON.getString("description"));
}
Recently, I found out json2pojo useful tool for json parsing, works with anything Jackson,Gson,Java etc.
Hope this will help you.
Try this
JSONObject weatherObject = new JSONObject(result);
JSONArray wArray = weatherObject.getJSONArray("weather");
for (int i = 0; i < wArray.length(); i++) {
JSONObject wObject = wArray.getJSONObject(i);
if(wObject.has("description")) {
Log.d("TAG", wObject.getString("description"));
}
if(wObject.has("main")) {
Log.d("TAG", wObject.getString("main"));
}
}
Use this
JSONObject weatherArray = new JSONObject(result);
JSONArray wArray = new JSONArray("weather");
String mainWeather = ((JSONObject)wArray.getJSONObject(0)).getString("main");
String mainDescription = ((JSONObject)wArray.getJSONObject(0)).getString("description");
Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();