Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch data of API through JSONArray

Tags:

java

json

android

//My API link
//http://gdata.youtube.com/feeds/base/videos?max-results=10&start-//index=1&alt=json&orderby=published&author=astrobixweb

//String Method to fetech data from server
    public static String sendRequest(String url) {
        String result = "";
        try {

            HttpClient client = new DefaultHttpClient();
            HttpParams httpParameters = client.getParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
            HttpConnectionParams.setSoTimeout(httpParameters, 5000);
            HttpConnectionParams.setTcpNoDelay(httpParameters, true);
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            InputStream ips = response.getEntity().getContent();

            BufferedReader buf = new BufferedReader(new InputStreamReader(ips,
                    "UTF-8"));

            StringBuilder sb = new StringBuilder();
            String s;
            while (true) {
                s = buf.readLine();
                if (s == null || s.length() == 0)
                    break;
                sb.append(s);

            }
            buf.close();
            ips.close();
            result = sb.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
}


//Here is parser class 
    public static void GroupResult(String url){

            try{
                 JSONArray jsonarray,jsonArray1,jsonArray2 ;
                  JSONObject json ;

             response=GetJsonObject.sendRequest(url);
             //data comes into response variable
             if(response == null){
                    return;
                }

                jsonarray = new JSONArray("["+response+"]");
                json = jsonarray.getJSONObject(0);
                String feed = (json.getString("feed"));

                Log.v("feed", ""+feed);

                //try{


                    jsonarray = new JSONArray("["+feed+"]");

                    json = jsonarray.getJSONObject(0);

                    String entry  = json.getString("entry");

                    jsonarray = new JSONArray(entry);

                    for (int i = 0; i < jsonarray.length(); i++)
            {
                mData=new AstrobixData();
                json = jsonarray.getJSONObject(i);

                   String title_array  = json.getString("title");
                   jsonArray1 = new JSONArray("["+title_array+"]");
                   String title = jsonArray1.getJSONObject(0).getString("$t");


                       String imagepath=json.getString("content");
                       jsonArray2=new JSONArray("["+imagepath+"]");
                       String urliamge=jsonArray1.getJSONObject(0).getString("$t");
                   }





              //  mData.SetTitle(title);
              //  mList.add(mData);

        }        
                }
                   // Log.v("title", ""+title_list);
            }
    } 

Someone please help to fetch the data of this API link. i have to tried and i have to fetched all data in String variable though http. but i want to 2 things from this API but i am not able to fetch these are:-

  1. title: "Sun,Moon, Mars, Rahu and Jupiter Antardasha during Sun's Mahadasha"
  2. Image:

    image

like image 883
FarhaSameer786 Avatar asked May 12 '26 23:05

FarhaSameer786


1 Answers

Step 1 : copy the WEBSERVICE URL and paste in to your browser , this will hit the web service and will show you the response , use chrome will be more helpful to see the JSON response

Step 2 : analyse the structure of your JSON response first of all you will be reading the complete response as a String

create a JSON OBJECT from the String

now convert that JSON object into a JSONARRAY object ,

now that you have a JSONARRAY

iterate the JSON Array and store one by one Object

inside the iteration loop for JSON array , for each JSON OBJECT call the value by their name see in JSON you have key value pairs

you can call JSONOBJECT.getString("variable name which retrieves String ");

or you can get other datatypes like this also

try this on your own , post me the status , will be responding you with modified code afterwards ===================================================================

I tried to resolve it for you , here is the class

package com.hussain.StackOverFlow;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class FarhaSameer1 {

    public static void main(String[] args) 
    {
        String asd = FarhaSameer1.sendRequest("http://gdata.youtube.com/feeds/base/videos?max-results=10&start-//index=1&alt=json&orderby=published&author=astrobixweb");
        FarhaSameer1.parseFromJSONResponse(asd);
    }
    // API link
    // http://gdata.youtube.com/feeds/base/videos?max-results=10&start-//index=1&alt=json&orderby=published&author=astrobixweb
    // String Method to fetech data from server
    public static String sendRequest(String url) {
        String result = "";
        try {
            HttpClient client = new DefaultHttpClient();
            HttpParams httpParameters = client.getParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
            HttpConnectionParams.setSoTimeout(httpParameters, 5000);
            HttpConnectionParams.setTcpNoDelay(httpParameters, true);
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            InputStream ips = response.getEntity().getContent();
            BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
            StringBuilder sb = new StringBuilder();
            String s;
            while (true) {
                s = buf.readLine();
                if (s == null || s.length() == 0)
                    break;
                sb.append(s);
            }
            buf.close();
            ips.close();
            result = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    public static void parseFromJSONResponse(String respo) 
    {
        JSONObject myjson;
        try 
        {
            myjson = new JSONObject(respo);
            JSONObject jsonObj1 = myjson.getJSONObject("feed");
            JSONArray jsonObj2 = jsonObj1.getJSONArray("entry");
            JSONObject jsonObj3 = jsonObj2.getJSONObject(0);
            System.out.println(jsonObj3.getJSONObject("content"));
            System.out.println("here ===>>>"+jsonObj3.getJSONObject("content").get("$t").toString());
        } 
        catch (JSONException e) {
            e.printStackTrace();
        }
    }   
}

see the first method is the same as you wrote it in the second method i am trying to traverse the JSON response step by step. see you have to be careful about your JSON response

1 : your complete response is a JSON OBJECT

2 : if any element is written like

"some key name " : { " some value " }

this is a JSON Object

3 : if any element is writen like

 "some key name " :  " some value " 

this is value inside you json object which you can get by

jsonObject.getString("key name")

4 : if any element is writen like

"some key name " : [ " some value " ]

then this is a JSON Array and you have to take it in to a JSON ARRAY and then traverse its elements by

jsonObject.getJSONARRAY("key name for JSON ARRAY IN RESPONSE ")

and then you can traverse the elements of the JSON ARRAY by

`jsonArrayObj.get(0);`

now you can traverse and retrieve the value you want , post me if any help needed further

like image 98
Hussain Akhtar Wahid 'Ghouri' Avatar answered May 15 '26 13:05

Hussain Akhtar Wahid 'Ghouri'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!