Java – How to get API data via JSONArray

How to get API data via JSONArray… here is a solution to the problem.

How to get API data via JSONArray

//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);
            }
    } 

Please help bring the data linked by this API. I have to try, I have to get all the data in the String variable via http. But I want to do two things from this API
But I can’t get these :-

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

    image

Solution

STEP 1: COPY AND PASTE THE WEBSERVICE URL INTO YOUR BROWSER, THIS WILL ACCESS THE WEB SERVICE AND DISPLAY THE RESPONSE, USING CHROME WILL BE MORE HELPFUL TO SEE THE JSON RESPONSE

Step 2: Analyze the structure of the JSON response
First, you will read the full response as a string

Create a JSON object from the string

NOW CONVERT THE JSON OBJECT TO A JSONARRAY OBJECT

NOW YOU HAVE A JSONARRAY

Iterate through the JSON array and store the Objects one by one

IN THE ITERATION LOOP OF THE JSON ARRAY, THEIR VALUES ARE CALLED FOR EACH JASON OBJECT
name
See in JSON that you have key-value pairs

YOU CAN CALL JSONOBJECT.GETSTRING(“GET THE VARIABLE NAME OF THE STRING”);

Or you can also get other data types like this

Try it yourself, send me the status and I’ll get back to you with the modified code
And then
================================================ =================

I tried to solve it for you, this 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();
        }
    }   
}

Look at the first method as you wrote
In the second method, I’m trying to walk through the JSON response step by step.
See you have to be careful with your JSON response

1: Your full response is a JSON object

2 : If any element is written

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

This is a JSON object

3 : If any element is written like this

 "some key name " :  " some value " 

This is the value in your JSON object that you can pass through

jsonObject.getString("key name")

4 : If any element is written as

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

Then this is a JSON Array, and you have to bring it into a JSON ARRAY and then iterate through its elements

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

YOU CAN THEN TRAVERSE

THE ELEMENTS OF THE JSON ARRAY

`jsonArrayObj.get(0); `

Now you can iterate through and retrieve the values you want, please email me if you need further help

Related Problems and Solutions