如何通过JSONArray获取API的数据 [英] How to fetch data of API through JSONArray

查看:186
本文介绍了如何通过JSONArray获取API的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

//字符串方法fetech来自服务器的数据
    公共静态字符串sendRequest将(字符串URL){
        字符串结果=;
        尝试 {

            HttpClient的客户端=新DefaultHttpClient();
            的HttpParams httpParameters = client.getParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters,5000);
            HttpConnectionParams.setSoTimeout(httpParameters,5000);
            HttpConnectionParams.setTcpNoDelay(httpParameters,真正的);
            HTTPGET请求=新HTTPGET();
            request.setURI(新的URI(URL));
            HTT presponse响应= client.execute(要求);
            InputStream的IPS = response.getEntity()的getContent()。

            的BufferedReader BUF =新的BufferedReader(新InputStreamReader的(IPS,
                    UTF-8));

            StringBuilder的SB =新的StringBuilder();
            字符串s;
            而(真){
                S = buf.readLine();
                如果(S == NULL || s.length()== 0)
                    打破;
                sb.append(多个);

            }
            buf.close();
            ips.close();
            结果= sb.toString();

        }赶上(例外五){
            e.printStackTrace();
        }

        返回结果;
    }
}


//这里是解析器类
    公共静态无效的Grou presult(字符串URL){

            尝试{
                 JSONArray jsonarray,jsonArray1,jsonArray2;
                  的JSONObject JSON;

             响应= GetJsonObject.sendRequest(URL);
             //数据进入响应变量
             如果(响应== NULL){
                    返回;
                }

                jsonarray =新JSONArray([+响应+]);
                JSON = jsonarray.getJSONObject(0);
                串料=(json.getString(饲料));

                Log.v(饲料,+饲料);

                //尝试{


                    jsonarray =新JSONArray([+饲料+]);

                    JSON = jsonarray.getJSONObject(0);

                    字符串项= json.getString(入门);

                    jsonarray =新JSONArray(项);

                    的for(int i = 0; I< jsonarray.length();我++)
            {
                MDATA =新AstrobixData();
                JSON = jsonarray.getJSONObject(ⅰ);

                   字符串title_array = json.getString(标题);
                   jsonArray1 =新JSONArray([+ title_array +]);
                   字符串标题= jsonArray1.getJSONObject(0).getString($ T);


                       字符串的ImagePath = json.getString(内容);
                       jsonArray2 =新JSONArray([+的ImagePath +]);
                       字符串urliamge = jsonArray1.getJSONObject(0).getString($ T);
                   }





              // mData.SetTitle(职称);
              // mList.add(MDATA);

        }
                }
                   // Log.v(标题,+ title_list);
            }
    }
 

有人请帮助来获取这个API链路的数据。我要尝试,我必须取出的字符串变量,虽然HTTP的所有数据。但我想两件事情,从这个API 但我不能够获取它们是: -

  1. 标题:太阳,月亮,火星,罗喉和木星Antardasha在Sun Mahadasha
  2. 图片:

解决方案

第1步:复制WebService的URL并粘贴到浏览器,这将打击网络服务,并会告诉你的反应,使用Chrome会更有帮助看到JSON响应

步骤2:分析你的JSON响应的结构 首先,你将阅读作为一个字符串的完全缓解

从字符串创建一个JSON对象

现在将其转换JSON对象到JSONARRAY对象,

现在,你有一个JSONARRAY

一个对象遍历JSON阵列和存储一个

的迭代循环的JSON数组中,每个JSON对象通过调用值的 名称 看到JSON你有键值对

您可以拨打JSONOBJECT.getString(它检索字符串变量名);

或者你可以得到其他数据类型这样也

试试这个你自己的,后我的状态,就会响应你修改code 之后  ================================================== =================

我试图解决这个问题对你来说,这里是班

 包com.hussain.StackOverFlow;

进口java.io.BufferedReader中;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.net.URI中;
进口的java.util.ArrayList;

进口org.apache.http.Htt presponse;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.params.HttpConnectionParams;
进口org.apache.http.params.HttpParams;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;


公共类FarhaSameer1 {

    公共静态无效的主要(字串[] args)
    {
        字符串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链接
    // http://gdata.youtube.com/feeds/base/videos?max-results=10&start-//index=1&alt=json&orderby=published&author=astrobixweb
    //字符串方法fetech来自服务器的数据
    公共静态字符串sendRequest将(字符串URL){
        字符串结果=;
        尝试 {
            HttpClient的客户端=新DefaultHttpClient();
            的HttpParams httpParameters = client.getParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters,5000);
            HttpConnectionParams.setSoTimeout(httpParameters,5000);
            HttpConnectionParams.setTcpNoDelay(httpParameters,真正的);
            HTTPGET请求=新HTTPGET();
            request.setURI(新的URI(URL));
            HTT presponse响应= client.execute(要求);
            InputStream的IPS = response.getEntity()的getContent()。
            的BufferedReader BUF =新的BufferedReader(新的InputStreamReader(IPSUTF-8));
            StringBuilder的SB =新的StringBuilder();
            字符串s;
            而(真){
                S = buf.readLine();
                如果(S == NULL || s.length()== 0)
                    打破;
                sb.append(多个);
            }
            buf.close();
            ips.close();
            结果= sb.toString();
        }赶上(例外五){
            e.printStackTrace();
        }
        返回结果;
    }
    公共静态无效parseFromJSONResponse(字符串respo)
    {
        的JSONObject myjson;
        尝试
        {
            myjson =新的JSONObject(respo);
            JSONObject的jsonObj1 = myjson.getJSONObject(饲料);
            JSONArray jsonObj2 = jsonObj1.getJSONArray(输入);
            的JSONObject jsonObj3 = jsonObj2.getJSONObject(0);
            的System.out.println(jsonObj3.getJSONObject(内容));
            的System.out.println(在这里===>>>中。+ jsonObj3.getJSONObject(内容)获得($ T)的toString());
        }
        赶上(JSONException E){
            e.printStackTrace();
        }
    }
}
 

请参阅第一种方法是一样的,你写的 在第二个方法,我想遍历一步JSON响应的一步。 看你要小心你的JSON响应

1:你完全反应是一个JSON对象

2:如果任何元素是这样写

 一些主要的名字:{一些价值}
 

这是一个JSON对象

3:如果任何元素writen像

 一些主要的名字:一些价值
 

这是里面的值,你的JSON对象,你可以通过

获得

  jsonObject.getString(键名)
 

4:如果任何元素writen像

 一些主要的名字:一些价值]
 

那么这是一个JSON数组,你必须把它在一个JSON数组,然后通过

遍历其元素

  jsonObject.getJSONARRAY(对JSON数组中的响应键名)
 

然后就可以通过

遍历JSON数组中的元素

 `jsonArrayObj.get(0);`
 

现在,您可以遍历和获取你想要的值,如果任何帮助,需要进一步后我

//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:

解决方案

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

这篇关于如何通过JSONArray获取API的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆