sam_k
sam_k

Reputation: 6023

How to get response from any url in json for Android and than after response I want to parse it

I want to know about how json works and how we can get response form url and then after I want to parse this response.

Upvotes: 1

Views: 22457

Answers (4)

Karthik
Karthik

Reputation: 391

Regarding JSON working principle and details have a look at this site http://www.json.org/ and regarding the packet format you can have a look at this one http://json.org/example.html

and regarding the proceesing aof packets i will show you a code which will work

HomeActivity.java

package net.ajzele.demo.andy1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;

public class HomeActivity extends ListActivity {
    JSONObject jo;

    /** Called when the activity is first created. */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.fetch()));
    }

    public ArrayList<String> fetch() {
        ArrayList<String> listItems = new ArrayList<String>();

        try {
            URL tw = new URL("http://twitter.com/statuses/public_timeline.json");
            URLConnection tc = tw.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

            String line;
            while ((line = in.readLine()) != null) {
                JSONArray ja = new JSONArray(line);

                /*
                 * for (int i = 0; i < ja.length(); i++) { //jo = (JSONObject) ja.get(i); Log.v(null,String.valueOf(ja.get(i)));
                 * //listItems.add(jo.getString("text"));
                 * 
                 * }
                 */
                JSONObject jObj;
                try {
                    jObj = new JSONObject(line);
                    JSONArray jArr = jObj.getJSONArray("filelist");
                    JSONObject jObj2 = jArr.getJSONObject(0);
                    Log.v(null, jObj2.getString("filename"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }

        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return listItems;
    }
}

Upvotes: 1

Ravishankar V
Ravishankar V

Reputation: 323

The link by Ben Williams I think is quite comprehensive in how json works. To make coding easier I would recommend the GSON library. I have used it quite extensively in my projects and has saved quite a bit of code.

Upvotes: 1

Dinash
Dinash

Reputation: 3047

try this... I used it...

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

     setListAdapter(new ArrayAdapter(this,
     android.R.layout.simple_list_item_1,
     this.fetchTwitterPublicTimeline()));

}

public ArrayList<String> fetchTwitterPublicTimeline() {
    ArrayList<String> listItems = new ArrayList<String>();

    try {
        URL twitter = new URL(
                "http://twitter.com/statuses/public_timeline.json");
        URLConnection tc = twitter.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(tc
                .getInputStream()));

        String line;
        while ((line = in.readLine()) != null) {
            JSONArray ja = new JSONArray(line);
            System.out.println(line);
            for (int i = 0; i < ja.length(); i++) {
                JSONObject jo = (JSONObject) ja.get(i);
                listItems.add(jo.getString("text"));
            }
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block e.printStackTrace(); } catch
    } catch (IOException e) { // TODO Auto-generated catch block
                                // e.printStackTrace();
    } catch (JSONException e) { // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return listItems;
}

Place it inside your activity...

Upvotes: 1

Rejinderi
Rejinderi

Reputation: 11844

to understand json read this link..

http://secretgeek.net/json_3mins.asp

you can find "json tutorials" on android

first thing you have to do is to get the response text.

private String getResponseText(String stringUrl) throws IOException
{
    StringBuilder response  = new StringBuilder();

    URL url = new URL(stringUrl);
    HttpURLConnection httpconn = (HttpURLConnection)url.openConnection();
    if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK)
    {
        BufferedReader input = new BufferedReader(new InputStreamReader(httpconn.getInputStream()),8192);
        String strLine = null;
        while ((strLine = input.readLine()) != null)
        {
            response.append(strLine);
        }
        input.close();
    }
    return response.toString();
}

In which after that you will take the response text and parse it as a json root object like so

String responseText = GetResponseText(requestUrl);
JSONObject mainResponseObject = new JSONObject(responseText);

and then according to the structure of the data you parse the JSONObject with the following classes: JSONObject JSONArray

and get the values using the get methods defined on the classes, check them on the documentation.

http://developer.android.com/reference/org/json/JSONObject.html

there are a lot of examples on the net do search for them..

Upvotes: 7

Related Questions