views:

48

answers:

2

Hi , Im brand new to Android Application development and I am working on an application that will get an RSS feed from a specific url that returns JSON data , what I am wondering is what is the best way to translate this from JSON to populate the list ,

I was thinking of making objects to hold the individual posts and then create a list of them from the json but is this the best way it seems a little rough

Just looking for idea on how others perform this action May also be helpful to other beginners as no concrete reference base is around for this subject.

thanks chris

+1  A: 

The android API has built in support for handling JSON data which is helpful for parsing. It uses the classes shown here: http://www.json.org/java/

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

At a high level, You can create a JSONObject by simply passing the entire JSON string into its constructor. From there it offers a list of get methods to pull primitive types, strings, or nested JSON objects out.

If you want to keep the posts saved, I would still parse the JSON data into an object for storage, otherwise you could just create a list from the data returned directly from the JSON objects.

Brad Gardner
A: 

Very basic example:

String resultString = "{"name":"Fred Nurke", "age":"56"}";
JSONObject jobj = new JSONObject(resultString); /*This converts the string 
                                                  into members of the JSON Object which   
                                                  you can then manipulate*/
Log.d(jobj.getString("name")+ " is " + jobj.getString("age") + " years old");

As I said that is a very basic example of working with JSON in Android. What you'll probably be dealing with is not just a JSONObject, but a JSONArray, which as the name implies is a special Array class of JSONObjects.

Working with a JSONArray can be done as follows: (Assume we've filled the resultString already)

JSONArray jsonArr = new JSONArray(resultString);
JSONObject jsonobj;
for(int i = 0; i < jsonArr.length(); i++){
    jsonobj = JSONArray.getJSONObject(i);
}

Once you have your JSONObject you can start working with it in the same manner as above.

Hope that helps.

purserj