I am working on parsing a website in my application.
This is the website: https://raw.github.com/currencybot/open-exchange-rates/master/latest.json
Since I have had some trouble with this, I first tried to get the entire website using a class that extends AsyncTask.
Here is the code which gets EVERYTHING from the website above:
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls)
{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try
{
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
}
However, if you go to the website, I only want the portion after rates. I have to edit the above code so it only returns what I need.
Based on what I understand, I know that I need to change String response to an ArrayList, and I need to change the while loop, but I don’t know what I should do exactly.
I tried using the following code to change the method, but it did NOT work.
private class DownloadWebPageTask extends AsyncTask<String, Void, ArrayList<String>> {
@Override
protected ArrayList<String> doInBackground(String... urls)
{
ArrayList<String> response = new ArrayList<String>();
for (String url : urls)
{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try
{
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = response.toString();
while ((s = buffer.readLine()) != null)
{
JSONArray ja = new JSONArray(s);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
response.add(jo.getString("rates"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
}
Any help would be greatly appreciated.
@Dheeraj, UPDATE:
while ((s = buffer.readLine()) != null)
{
JSONArray ja = new JSONObject().getJSONArray("rates");
response.add(ja.toString());
}
This is what I have so far Dheeraj. I am stuck on how to provide the buffer to a JSONObject. Can you help me?
JSONObject.JSONObjectget the value of “rates” as anotherJSONObjectusinggetJSONObject("rates").Here’s the code: