How to retrieve a JSON as an object in Android?

Android Java retrieve JSON values and store as object in list

  • I would like to connect to Api link which can have multiple pages and store all the JSON values as a object in a list. http://www.gw2spidy.com/api/v0.9/json/item-search/Iron/0 Problems that I have so far encountered and unable to solve. Return type of doInBackground as constructor class apiRootObject and how to deserialize the Json result, its logical why it doesnt work since I its extended from AsyncTask but i do not know how to work around this problem or what other road to take. This is the code I have so far. Calling the initial function in my Activity.java String userSearchRequest = search_activity_data.getString("userSearchRequest"); String URL = "http://www.gw2spidy.com/api/v0.9/json/item-search/" + userSearchRequest + "/"; //Api link example with multiple pages = "http://www.gw2spidy.com/api/v0.9/json/item-search/Iron" AsyncFetch parkingInfoFetch = new AsyncFetch(this); parkingInfoFetch.setOnResponse(this); parkingInfoFetch.execute(URL); My AsyncFetch.java class which is called from aboves code public class AsyncFetch extends AsyncTask { public AsyncFetch(Context context) { this.context = context; } private Context context; private JSONObject jsonObject; private onResponse onResponse; public void setOnResponse(onResponse onResponse) { this.onResponse = onResponse; } @Override protected apiRootObject doInBackground(String... params) { //Incompatible return type // TODO Auto-generated method stub apiRootObject apiRootObject = null; apiRootObject tempApiRootObject = null; int page = 0; try { do { HttpGet get = new HttpGet(params[0] + page); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); //jsonObject = new JSONObject(result); tempApiRootObject = /*Deserialize into <RootObject>(result)*/ if (apiRootObject == null){ apiRootObject = tempApiRootObject; } else{ apiRootObject.results.addAll(tempApiRootObject.results); apiRootObject.count += tempApiRootObject.count; } page++; } while(tempApiRootObject.last_page != tempApiRootObject.page); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return apiRootObject; } @Override protected void onPostExecute(JSONObject result) { // TODO Auto-generated method stub super.onPostExecute(result); this.onResponse.onResponse(result); } public interface onResponse { public void onResponse(JSONObject object); } } And back in the activity.java everything is being added to the list in the onResponse function. public void onResponse(JSONObject object) {//Still expecting a JSONObject while I am changing this return type Log.i("gw2Log", object.toString()); apiRootObject resultClass = new apiRootObject(); try { resultClass.setCount(object.getInt("count")); resultClass.setPage(object.getInt("page")); resultClass.setLast_page(object.getInt("last_page")); resultClass.setTotal(object.getInt("total")); JSONArray list = new JSONArray(object.getString("results")); for (int i = 0; i < resultClass.getCount(); i++) { JSONObject resultsObject = list.getJSONObject(i); apiResults temp = new apiResults(); temp.setData_id(resultsObject .getInt("data_id")); temp.setName(resultsObject .getString("name")); temp.setRarity(resultsObject .getInt("rarity")); temp.setRestriction_level(resultsObject .getInt("restriction_level")); temp.setImg(resultsObject .getString("img")); temp.setType_id(resultsObject .getInt("type_id")); temp.setSub_type_id(resultsObject .getInt("sub_type_id")); temp.setPrice_last_changed(resultsObject .getString("price_last_changed")); temp.setMax_offer_unit_price(resultsObject .getInt("max_offer_unit_price")); temp.setMin_sale_unit_price(resultsObject .getInt("min_sale_unit_price")); temp.setOffer_availability(resultsObject .getInt("offer_availability")); temp.setSale_availability(resultsObject .getInt("sale_availability")); temp.setSale_price_change_last_hour(resultsObject .getInt("sale_price_change_last_hour")); temp.setOffer_price_change_last_hour(resultsObject .getInt("offer_price_change_last_hour")); resultClass.addObject(temp); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(int i = 0; i < resultClass.count; i++) { Log.i("gw2Log", resultClass.getObject(i).name); } } Ofcourse there are also 2 constructor classes apiResults and apiRootObject. EDIT: If you take the link on the top of the question you get a lot of JSON values returned, every page can have 50 of these results if there are more a new page is created. I want to connect to this Api link, and retrieve all values that are being returned. If there are multiple pages it needs to loop through all existing pages and add these JSON values to the exact same list. I have asked a similiar question before in c# and here I've got it working but I now need the exact same in Android Java. For android java i was told i need to use AsyncTask in order to make a connection and do all of this in the background of the application. If there is a better or easier way, please enlighten me.

  • Answer:

    It might not be too late to use http://square.github.io/retrofit/ .

Krijn van der Burg at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

try this @Override protected apiRootObject doInBackground(String... params) { //Incompatible return type // TODO Auto-generated method stub apiRootObject apiRootObject = null; apiRootObject tempApiRootObject = null; List<apiRootObject> myList=new ArrayList<apiRootObject>(); int page = 0; try { do { HttpGet get = new HttpGet(params[0] + page); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); jsonObject = new JSONObject(result); //handling json exceptions if(jsonObejct!=null && !jsonObject.isNull("page")&&..){ tempApiRootObject.page=jsonObject.getString("page"); tempApiRootObject.last_page=jsonObject.getString("last_page"); //here we put the results in the tempsApiRootObject JSONArray ja = jsonObject.getJSONArray("results"); for (int i = 0; i < ja.length(); i++) { JSONObject c = ja.getJSONObject(i);//this is an item int data_id= c.getInt("data_id"); String name= c.getString("name"); //the other values //here you add them in your arraylist of <apiResults> (*) } //and here we add the arraylist in (*) to tempApiRootObject myList.add(tempApiRootObject); /* if (apiRootObject == null){ apiRootObject = tempApiRootObject; } else{ apiRootObject.results.addAll(tempApiRootObject.results); apiRootObject.count += tempApiRootObject.count; }*/ i didn't understand this }page++; } while(tempApiRootObject.last_page != tempApiRootObject.page); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return myList// apiRootObject; } and this public void onResponse(List<apiRootObject> myList) { for(int i=0;i++;i<myList.size()){ apiRootObject resultClass =myList.get(i); //do something } }

Charaf Eddine Mechalikh

gson is the easiest way to convert json into a class. //your class public class Foo { public final int bar; public final String bazz; public foo(int bar, String bazz) { this.bar = bar; this.bazz = bazz; } } //your json { "bar" : 4, "bazz" : "interesting content" } //your gson call Gson gson = new Gson(); Foo foo = gson.fromJson(json, Foo.class); you can even do nested objects and it will deserialize them all. public class FooHaver { public final String prop1; public final Foo foo; } //your json { "prop1" : "more content", "foo" : { "bar" : 4, "bazz" : "even more content" } } you can also do json arrays as arrays or as a java List of any type you want

Jordan Davidson

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.