How to parse json similar inner objects? - android

I am having the following code
{"sports" :[{"name" :"baseball","id" :1,"links" :{"api" :{"sports" :{"href" :"http://api.espn.com/v1/sports/baseball"},"news" :{"href" :"http://api.espn.com/v1/sports/baseball/news"},"notes" :{"href" :"http://api.espn.com/v1/sports/baseball/news/notes"},"headlines" :{"href" :"http://api.espn.com/v1/sports/baseball/news/headlines"},"events" :{"href" :"http://api.espn.com/v1/sports/baseball/events"}}},"leagues" :[{"name" :"Major League Baseball","abbreviation" :"mlb","id" :10,"groupId" :9,"shortName" :"MLB","season" :{"year" :2012,"type" :2,"description" :"regular","startDate" :"2012-03-27T19:00:00Z","endDate" :"2012-10-05T06:59:59Z"},"week" :{"number" :23,"startDate" :"2012-08-28T19:00:00Z","endDate" :"2012-09-04T18:59:00Z"}}]}],"timestamp" :"2012-08-30T18:01:29Z","status" :"success"}
I want to parse the json objects, in sports object we are having another sports object how to parse inner json objects with array of elements.
I am trying with the following code:
public class BaseballActivity extends ListActivity{
private static String url = "http://api.espn.com/v1/sports/baseball?apikey=h29yphwtf7893hktfbn7cd5g";
private static final String TAG_SPORTS = "sports";
private static final String TAG_ID = "id";
private static final String TAG_TIMESTAMP = "timestamp";
private static final String TAG_NAME = "name";
private static final String TAG_NEWS = "news";
private static final String TAG_HEADLINES = "headlines";
private static final String TAG_LINKS = "links";
private static final String TAG_API = "api";
private static final String TAG_SPORTS1 = "sports";
private static final String TAG_HREF = "href";
JSONArray sports = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// HashMap for ListView
ArrayList<HashMap<String, String>> sportsList = new ArrayList<HashMap<String, String>>();
// creating Json parser instance
JSONParser jParser = new JSONParser();
// getting Json String from url
JSONObject json = jParser.getJSONFromUrl(url);
try{
// Getting Array of Contacts
sports = json.getJSONArray(TAG_SPORTS);
// looping through All Contacts
for(int i = 0; i < sports.length(); i++){
JSONObject c = sports.getJSONObject(i);
//String news = c.getString(TAG_NEWS);
// String headlines = c.getString(TAG_HEADLINES);
String name = c.getString(TAG_NAME);
// String timestamp = c.getString(TAG_TIMESTAMP);
String id = c.getString(TAG_ID);
// JSONObject links = c.getJSONObject(TAG_LINKS);
// JSONObject api = c.getJSONObject(TAG_API);
// JSONObject sports = c.getJSONObject(TAG_SPORTS1);
// String href = c.getString(TAG_HREF);
HashMap<String, String> map = new HashMap<String, String>();
// map.put(TAG_TIMESTAMP, timestamp);
map.put(TAG_NAME, name);
// map.put(TAG_NEWS, news);
// map.put(TAG_HEADLINES, headlines);
map.put(TAG_ID, id);
// map.put(TAG_HREF, href);
sportsList.add(map);
}
}
catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, sportsList,
R.layout.list_item,
new String[]{TAG_NAME,TAG_ID} , new int[] {
R.id.id,R.id.name});
setListAdapter(adapter);
}}
ublic class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject 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 jObj;
}}
Name and id can be displayed when i try to parse inner objects there is no output please help me.

You should have a class Sports that has the objects that come on your JSON string
Than this should do the job for you
JSONObject jObject = new JSONObject(json);
jObject.getJSONObject("sports");
this will make a JSONOBJECT outof your JsonString
Than you will use Googles Gson library to do the following
Gson gson = new Gson();
Sports sports = gson.fromJson(jObject.toString(), Sports.class);
I advise u to have a class to handle all the WebReqeuisitions and not have this code on your Activitys makes your project more structured and your code will be cleaner

Related

Android - retrieving json via HTTPS

I've a problem with parsing json from facebook graph api.
When I'm using facebook URL:https://graph.facebook.com/interstacjapl/feed?access_token=MyTOKEN to grab json it's no working, but when I copied that json (it works in browser) and paste to my webiste http://mywebsite/fb.json and change site URL in the code, it works good.
When I'm using fb graph URL it shows error:
W/System.err(5534): org.json.JSONException: No value for data
Is this problem with parsing from https or URL or code?
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject 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 jObj;
}
}
MainActivity
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "https://graph.facebook.com/interstacjapl/feed?access_token=CAACEdEose0cBANLR...";
//JSON Node Names
private static final String TAG = "data";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "message";
private static final String TAG_API = "type";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_ID,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
This works
String reply = "";
BufferedReader inStream = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(httpRequest);
inStream = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer("");
String line = "";
while ((line = inStream.readLine()) != null) {
buffer.append(line);
}
inStream.close();
reply = buffer.toString();
} catch (Exception e) {
//Handle Execptions
}

Android -Connection Error

I need to parse the link given below
http://192.168.1.91/projects/gprs/
If I open this in my browser i get like the response given below,
{"machine":[{"id":"3688","machine_code":"999999","di1":"0","di2":"1","di3":"0","di4":"1","di5":"0","di6":"1","di7":"0","di8":"1"}]}
But In my project ,logcat shows connection refused
I need to get the values in textview .How to achieve this?
The java codings is pasted below,
AndroidJSONParsingActivity.java
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://192.168.1.91/projects/gprs/";
// JSON Node names
private static final String TAG_CONTACTS = "machine";
private static final String TAG_ID = "di1";
private static final String TAG_NAME = "di2";
private static final String TAG_EMAIL = "di3";
private static final String TAG_ADDRESS = "di4";
private static final String TAG_GENDER = "di5";
private static final String TAG_PHONE = "di5";
private static final String TAG_PHONE_MOBILE = "di7";
private static final String TAG_PHONE_HOME = "di8";
//private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_HOME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
}
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject 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 jObj;
}
}
Use below method to parse your response:
public void parseHttpResponse(String response){
JSONObject object;
try {
object = (JSONObject) new JSONTokener(response).nextValue();
JSONArray jsonArray = object.getJSONArray("machine");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String id=c.getString("id");
String machineCode=c.getString("machine_code");
//so as parse other
Log.v(TAG, "id: "+id+" machine code: "+machineCode);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Use :
parseHttpResponse("your_response_here");

Add images to ListView corresponding to its content, obtained from JSON response

I am using JSON parser to parse JSON Response, where i am able to get item names in ListView but i am not able to get images corresponding to it. where image url's are present in JSON response. How can i parse response to get images corresponding to items. Following is the code, Any one who know how to do this kindly help me it would be very useful.
Note: images and items are NOT Fixed
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "website/?JSON=get_recent_post";
// JSON Node names
private static final String TAG_POSTS = "posts";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_DATE = "date";
private static final String TAG_CONTENT = "content";
private static final String TAG_AUTHOR = "author";
private static final String TAG_NAME = "name";
// contacts JSONArray
JSONArray posts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
posts = json.getJSONArray(TAG_POSTS);
// looping through All Contacts
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String date = c.getString(TAG_DATE);
String content = c.getString(TAG_CONTENT);
// Phone number is agin JSON Object
JSONObject author = c.getJSONObject(TAG_AUTHOR);
String name = author.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put( TAG_DATE, date);
map.put( TAG_NAME, name);
map.put( TAG_CONTENT, content);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_TITLE, TAG_DATE, TAG_NAME, TAG_CONTENT }, new int[] {
R.id.name, R.id.email,R.id.mobile, R.id.content });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.name)).getText().toString();
String date = ((TextView) view.findViewById(R.id.email)).getText().toString();
String name = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
String content = ((TextView) view.findViewById(R.id.content)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_DATE, date);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_CONTENT, content);
startActivity(in);
}
});
}
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject 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 jObj;
}
}
SingleMenuItem.java
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_TITLE = "title";
private static final String TAG_DATE = "date";
private static final String TAG_NAME = "name";
private static final String TAG_CONTENT = "content";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String title = in.getStringExtra(TAG_TITLE);
String date = in.getStringExtra(TAG_DATE);
String name = in.getStringExtra(TAG_NAME);
String content = in.getStringExtra(TAG_CONTENT);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.email_label);
TextView lblDesc = (TextView) findViewById(R.id.mobile_label);
TextView lblCont = (TextView) findViewById(R.id.content_label);
lblName.setText(title);
lblCost.setText(date);
lblDesc.setText(name);
lblCont.setText(content);
}
}
You have to make your own adapter extending the BaseAdapter to have more freedom and flexibility...it's not too hard, you just have to bind the elements of the list row with the json data for the corresponding rows...on this binding you will also fetch the images, and assign to the ImageViews.
SimpleAdapter is meant for very simple stuff.

How to parse the following JSON?

Hi I am new to working on JSON Format Webservices .
I have the Json like....
{ "meta":{"success":1},
"Countries":
[[{"Id":"1","Name":"Gibraltar",
"Cities":
[[{"Id":"21","Name":"Gibraltar"}]]
},
{"Id":"2","Name":"Canada",
"Cities":
[[{"Id":"22","Name":"Toronto"},
{"Id":"39","Name":"Banff"}]]
},
{"Id":"4","Name":"Malta",
"Cities":
[[{"Id":"37","Name":"Valletta"}]]
},
{"Id":"51","Name":"Italy",
"Cities":
[[{"Id":"24","Name":"Sardinia"}]]
},
{"Id":"53","Name":"England",
"Cities":
[[{"Id":"23","Name":"London"},
{"Id":"38","Name":"Guildford"},
{"Id":"43","Name":"Petersfield"},
{"Id":"44","Name":"Isle of Wight"}]]
},
{"Id":"175","Name":"Hungary",
"Cities":
[[{"Id":"36","Name":"Budapest"}]]
}
]]
}
But I am unable to get the values .. while parsing as json Object.
I have tried to get the values like...
public class JSONParsing1 extends ListActivity {
private static String url = "http://wsapi.vr2020.com/countries.json";
private static final String TAG_META = "meta";
private static final String TAG_SUCCESS = "success";
private static final String TAG_COUNTRIES = "Countries";
private static final String TAG_ID = "Id";
private static final String TAG_NAME = "Name";
private static final String TAG_CITY = "Cities";
private static final String TAG_CITY_ID = "Id";
private static final String TAG_CITY_NANE = "Name";
private String id;
private String name;
private String city_id;
private String city_name;
JSONObject meta;
JSONArray Countries = null;
JSONArray Cities = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = jsonParser.getJSONFromUrl(url);
try {
meta = jsonObject.getJSONObject(TAG_META);
TextView startText = (TextView) findViewById(R.id.stat_textView);
startText.setText(meta.getString(TAG_SUCCESS));
} catch (Exception e) {
e.printStackTrace();
}
try {
Countries = meta.getJSONArray(TAG_COUNTRIES);
for (int i = 0; i < Countries.length(); i++) {
JSONObject obj = Countries.getJSONObject(i);
id = obj.getString(TAG_ID);
name = obj.getString(TAG_NAME);
JSONArray city = obj.getJSONArray(TAG_CITY);
for(int j = 0; j< city.length(); j++){
JSONObject cityobj = city.getJSONObject(j);
city_id = cityobj.getString(TAG_CITY_ID);
city_name = cityobj.getString(TAG_CITY_ID);
}
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
list.add(map);
}
} catch (Exception e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, list,
R.layout.list_items, new String[] { TAG_ID, TAG_NAME,
}, new int[] { R.id.id_textView,
R.id.name_textView, R.id.description_textView });
setListAdapter(adapter);
}
}
And JSON PArser Class is
public class JSONParser {
static InputStream is = null;
static JSONObject jsonObject = null;
static String json = "";
public JSONObject getJSONFromUrl(String url) {
try {
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 {
jsonObject = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jsonObject;
}
}
Can any one share how to Parse the above JSON?
Thanks in advance.
Parse Current Json as:
JSONObject jsonObj = new JSONObject(jsonStr);
// these 2 are strings
JSONObject c = jsonObj.getJSONObject("meta");
String success = c.getString("success");
JSONArray jsonarr = jsonObj.getJSONArray("Countries");
// lets loop through the JSONArray and get all the items
for (int i = 0; i < jsonarr.length(); i++) {
JSONArray jsonarra = jsonarr.getJSONArray(i);
// lets loop through the JSONArray and get all the items
for (int j = 0; j < jsonarra.length(); j++) {
JSONObject jsonarrtwo = jsonarra.getJSONObject(j);
// these 2 are strings
String str_id = jsonarrtwo.getString("id");
String str_Name = jsonarrtwo.getString("Name");
JSONArray jsonarr_cities = jsonarrtwo.getJSONArray("Cities");
// lets loop through the JSONArray and get all the items
for (int t = 0; t < jsonarr_cities.length(); t++) {
// printing the values to the logcat
JSONArray jsonarr_cities_one = jsonarrtwo.getJSONArray(t);
for (int tt = 0; tt < jsonarr_cities_one.length(); tt++) {
// printing the values to the logcat
JSONObject jsonarr_cities_two = jsonarr_cities_one.getJSONObject(tt);
// these 2 are strings
String str_idone = jsonarr_cities_two.getString("id");
String str_Nameone = jsonarr_cities_two.getString("Name");
}
}
}
}
for parsing json try this tuts:
http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/
for formatting json :
http://jsonviewer.stack.hu/
You can validate your json string by this tool http://jsonlint.com/
Your json string contains a json array of json array at the Countries tag and Cities tag.
Try something like this in your JSONParsing1 activity;
replace the line of code,
Countries = meta.getJSONArray(TAG_COUNTRIES);
with this line
Countries = new JSONArray(jsonObject.getJSONArray(TAG_COUNTRIES).toString());
replace the line of code,
JSONArray city = obj.getJSONArray(TAG_CITY);
with this line
JSONArray city = new JSONArray(obj.getJSONArray(TAG_CITY).toString());
It may help you to solve the problem. Try this way... ;)

How to download a JSON Object array from URL, and Store for Android App?

I'm trying to integrate an API into an android application I am writing, but am having a nightmare trying to get the JSON array. The API has a URL that returns a an JSON array, but having never used JSON before I have no idea how this works, or how to do it.
I've looked and found tons, and tons of examples, but nothing to explain why/how it is done. Any help understanding this would be greatly appreciated.
This is what I've ended up with, again with no understanding of JSON, it was a shot in the dark on my part (using examples/tutorials as a guide)...but it doesn't work :(
import org.json.*;
//Connect to URL
URL url = new URL("URL WOULD BE HERE");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.connect();
//Get Data from URL Link
int ok = connection.getResponseCode();
if (ok == 200) {
String line = null;
BufferedReader buffer = new BufferedReader(new java.io.InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
while ((line = buffer.readLine()) != null)
sb.append(line + '\n');
//FROM HERE ON I'm Kinda Lost & Guessed
JSONObject obj = (JSONObject) JSONValue.parse(sb.toString()); //ERROR HERE:complains it dosn't know what JSONValue is
JSONArray array = (JSONArray)obj.get("response");
for (int i=0; i < array.size(); i++) {
JSONObject list = (JSONObject) ((JSONObject)array.get(i)).get("list");
System.out.println(list.get("name")); //Used to debug
}
}
UPDATE/SOLUTION:
So, it turns out that there was nothing wrong w/t the code. I was missusing what I thought it returns. I thought it was a JSONObject array. In actuality it was a JSONObjects wrapped in an array, wrapped in a JSONObject.
For those interested/ having similar issues, this is what I ended up with. I broke it into two methods. First connect/download, then:
private String[] buildArrayList(String Json, String Find) {
String ret[] = null;
try {
JSONObject jObject = new JSONObject(Json);
JSONArray jArray = jObject.getJSONArray("response");
ret = new String[jArray.length()];
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String var = json_data.getString(Find);
ret[i] = var;
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
1) use webservice to download your required Json string
2) convert it to your desired object using Google Gson
Gson gson = new Gson();
MyClass C1 = gson.fromJson(strJson, MyClass.class);
Here you used JSONValue.parse() that is invalid.
Insted of that Line write this code:
JSONObject obj = new JSONObject(<String Value>);
Ok my friend, i solved the same problem in my app with the next code:
1.- Class to handle the Http request:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static JSONObject jObj1 = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
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();
//Log.e("JSONObject(JSONParser1):", json);
} catch (Exception e) {
Log.e("Buffer Error json1" +
"", "Error converting result json1:" + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
jObj1 = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser1:", "Error parsing data json1:" + e.toString());
}
// return JSON String
return jObj;
}
}
Later, a class to handle the json info (Arrays, Objects, String, etc...)
public class ListViewer extends ListActivity{
TextView UserName1;
TextView LastName1;
// url to make request
private static String url = "http://your.com/url";
// JSON Node names
public static final String TAG_COURSES = "Courses"; //JSONArray
//public static final String TAG_USER = "Users"; //JSONArray -unused here.
//Tags from JSon log.aspx All Data Courses.
public static final String TAG_COURSEID = "CourseId"; //Object from Courses
public static final String TAG_TITLE = "title";
public static final String TAG_INSTRUCTOR = "instructor";
public static final String TAG_LENGTH = "length";
public static final String TAG_RATING = "Rating"; //Object from Courses
public static final String TAG_SUBJECT = "subject";
public static final String TAG_DESCRIPTION = "description";
public static final String TAG_STATUS = "Status"; //Object from Courses
public static final String TAG_FIRSTNAME = "FirstName"; //Object from User
public static final String TAG_LASTNAME = "LastName"; //Object from User
// contacts JSONArray
JSONArray Courses = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lay_main);
// Hashmap for ListView
final ArrayList<HashMap<String, String>> coursesList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance (json2)
JSONParser2 jParser2 = new JSONParser2();
// getting JSON string from URL json2
final JSONObject json2 = jParser2.getJSONFromUrl(url);
try {
// Getting Array of Contacts
Courses = json2.getJSONArray(TAG_COURSES);
// looping through All Courses
for(int i = 0; i < Courses.length(); i++){
JSONObject courses1 = Courses.getJSONObject(i);
// Storing each json item in variable
String courseID = courses1.getString(TAG_COURSEID);
//String status = courses1.getString(TAG_STATUS);
String Title = courses1.getString(TAG_TITLE);
String instructor = courses1.getString(TAG_INSTRUCTOR);
String length = courses1.getString(TAG_LENGTH);
String rating = courses1.getString(TAG_RATING);
String subject = courses1.getString(TAG_SUBJECT);
String description = courses1.getString(TAG_DESCRIPTION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_COURSEID,courseID);
map.put(TAG_TITLE, Title);
map.put(TAG_INSTRUCTOR, instructor);
map.put(TAG_LENGTH, length);
map.put(TAG_RATING, rating);
map.put(TAG_SUBJECT, subject);
map.put(TAG_DESCRIPTION, description);
//adding HashList to ArrayList
coursesList.add(map);
}} //for Courses
catch (JSONException e) {
e.printStackTrace();
}
//Updating parsed JSON data into ListView
ListAdapter adapter = new SimpleAdapter(this, coursesList,
R.layout.list_courses,
new String[] { TAG_COURSEID, TAG_TITLE, TAG_INSTRUCTOR, TAG_LENGTH, TAG_RATING, TAG_SUBJECT, TAG_DESCRIPTION }, new int[] {
R.id.txt_courseid, R.id.txt_title, R.id.txt_instructor, R.id.txt_length, R.id.txt_rating, R.id.txt_topic, R.id.txt_description });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
//#Override --------check this override for onClick event---------
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String courseID = ((TextView) view.findViewById(R.id.txt_courseid)).getText().toString();
String Title = ((TextView) view.findViewById(R.id.txt_title)).getText().toString();
String instructor = ((TextView) view.findViewById(R.id.txt_instructor)).getText().toString();
String length = ((TextView) view.findViewById(R.id.txt_length)).getText().toString();
String rating = ((TextView) view.findViewById(R.id.txt_rating)).getText().toString();//Check place in layout
String subject = ((TextView) view.findViewById(R.id.txt_topic)).getText().toString();// <- HERE
String description = ((TextView) view.findViewById(R.id.txt_description)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleListItem.class);
in.putExtra(TAG_COURSEID, courseID);
in.putExtra(TAG_TITLE, Title);
in.putExtra(TAG_INSTRUCTOR, instructor);
in.putExtra(TAG_LENGTH, length);
in.putExtra(TAG_RATING, rating);
in.putExtra(TAG_SUBJECT, subject);
in.putExtra(TAG_DESCRIPTION, description);
startActivity(in);
}
});//lv.SetOnclickListener
}//onCreate
}// Activity
in this case, i'll get the Arrays, objects... Hope this give you ideas...

Categories

Resources