Reputation: 135
I am trying to get data from a JSON URL. Of course by AsyncTask. But the problem is the JSON file does not have Object. It is an array. JSON URL and api website
Can someone tell me how to create a JSONArray and JSONObject for this JSON file?!
Here is what I have done which makes the app stop working
//URL to get JSON Array
private static String url = "http://api.worldbank.org/countries/ir?format=json";
//JSON Node Names
private static final String TAG_OBJ = "user";
private static final String NAME = "name";
private static final String CAPITALCITY = "capitalCity";
.
.
.
class GetJSONTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... urls) {
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = JSONParser.getJson(url);
return json;
}
protected void onPostExecute(JSONObject json) {
//Getting JSON Array
try {
user = json.getJSONArray(TAG_OBJ);
JSONObject c = user.getJSONObject(0);
//Stroing JSON item in a Variable
String name = c.getString(NAME);
String capitalCity = c.getString(CAPITALCITY);
//Importing TextView
final TextView view1 = (TextView)findViewById(R.id.name);
final TextView view2 = (TextView)findViewById(R.id.capitalCity);
//Set JSON Data in TextView
view1.setText(name);
view2.setText(capitalCity);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 4697
Reputation: 1644
Change your MainActivity.java like below,
public class MainActivity extends Activity {
// URL to get JSON Array
private static String url = "http://api.worldbank.org/countries/ir?format=json";
// JSON Node Names
private static final String TAG_NAME = "name";
private static final String TAG_CAP_City = "capitalCity";
JSONArray responseArray = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetJSONTask().execute();
}
class GetJSONTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... arg0) {
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
String json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
// Getting JSON Array
responseArray = new JSONArray(result);
JSONArray parsedArray=responseArray.getJSONArray(1);
JSONObject c = parsedArray.getJSONObject(0);
// Storing JSON item in a Variable
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_CAP_City);
// Importing TextView
// final TextView uid = (TextView)findViewById(R.id.uid);
final TextView name1 = (TextView) findViewById(R.id.name);
final TextView email1 = (TextView) findViewById(R.id.email);
// Set JSON Data in TextView
// uid.setText(id);
name1.setText(name);
email1.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Also change JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public String getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
/*// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}*/
// return JSON String
return json;
}
}
Upvotes: 0
Reputation: 5295
Please note that i have used Strict Policy. You continue using Async Task and put my code in there. Here is my Code related to your requirement .
JsonParser.Java
package com.example.test;
import android.os.StrictMode;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
static JSONArray jArray = null;
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
// Making HTTP request
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jArray = new JSONArray(json);
// jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jArray;
}
}
MainActivity.java
package com.example.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Making HTTP request
String url = "http://api.worldbank.org/countries/ir?format=json";
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONArray json = jParser.getJSONFromUrl(url);
try {
JSONArray json2 = json.getJSONArray(1); // Your second Array in your json
for(int i=0;i<json2.length();i++){
JSONObject c = json2.getJSONObject(i);
// Storing JSON item in a Variable
String name = c.optString("name","");
String capitalCity = c.optString("capitalCity","");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Upvotes: 0
Reputation: 5295
Use JSON Array . Here is my code :-
String url = "http://api.androidhive.info/contacts/";
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
JSONArray begin = json.getJSONArray("contacts");
JSONObject c = begin.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString("id");
String name = c.getString("name");
String size = c.getString("email");
Put this in your Async
Upvotes: 1
Reputation: 5494
if(i<jArray.length()) {
JSONObject json_obj = jArray.getJSONObject(i); //get array object
name = json_obj.getString("your tag name"); fetch item here
}
Upvotes: 0