如何通过JSONArray获取API数据

时间:2013-09-23 10:53:26

标签: java android json

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

有人请帮助获取此API链接的数据。我必须尝试,我必须通过http获取String变量中的所有数据。但我想从这个API中获取2件事 但我无法取得这些: -

  1. 标题:"Sun,Moon, Mars, Rahu and Jupiter Antardasha during Sun's Mahadasha"
  2. 图片:

    image

1 个答案:

答案 0 :(得分:4)

第1步:复制WEBSERVICE网址并粘贴到您的浏览器中,这将点击Web服务并显示响应,使用chrome将更有助于查看JSON响应

第2步:分析JSON响应的结构 首先,您将以字符串

的形式阅读完整的响应

从String

创建一个JSON OBJECT

现在将该JSON对象转换为JSONARRAY对象,

现在你有一个JSONARRAY

迭代JSON数组并逐个存储Object

在JSON数组的迭代循环内,为每个JSON OBJECT调用它们的值 名称 在JSON中看到你有关键值对

你可以调用JSONOBJECT.getString(“检索String的变量名”);

或者您也可以获得其他类似的数据类型

自己尝试一下,发给我状态,会用修改后的代码回复你 然后  ================================================== =================

我试着为你解决,这是班级

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

看到第一个方法和你写的一样 在第二种方法中,我试图逐步遍历JSON响应。 看你必须小心你的JSON响应

1:您的完整回复是JSON OBJECT

2:如果任何元素写成

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

这是一个JSON对象

3:如果任何元素被写成

 "some key name " :  " some value " 

这是你可以通过

得到的json对象里面的值
jsonObject.getString("key name")

4:如果任何元素被写成

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

然后这是一个JSON数组,您必须将其带入JSON ARRAY,然后通过

遍历其元素
jsonObject.getJSONARRAY("key name for JSON ARRAY IN RESPONSE ")

然后你可以通过

遍历JSON ARRAY的元素
`jsonArrayObj.get(0);`

现在您可以遍历并检索您想要的值,如果需要进一步的帮助,请发送给我