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... ;)
Related
Hi i am completely new to android.please suggest me how to parse the below jsonresposne and get the values.any help please suggest me.i don't know how to parse because it contains both square bracket and curly bracket.
`[
{
"bus_schedule":[
{
"bus_route":[
{
"serviceDate":"2016-12-31",
"amenities":" VB King Size Semi Sleeper (2 plus 1) selected WIFI,Water,Bottle,Blankets,Snacks,Movie,Food,Emergency exit, Fire Extinguisher,Bus Hostess,CCTV,Emergency Contact Number",
"startCityName":"Coimbatore",
"departureTime":"21:00:00",
"fare":"499",
"endCityName":"Kanyakumari",
"arrivalTime":"06:00:00",
"operatorName":"RUN TO WIN",
"bus_id":"17",
"journeyHours":"9",
"available_seat":25,
"total_seats":34,
"seat_type":"semi sleeper"
}
],"boardingPoint":[
{
"boardingPointName":"Thudiyalur",
"boardingPointContact":"8883088820",
"boardingPointTime":"21:25:00",
"boardingPointId":"316",
"BusId":"17"
},`
my code is
`protected Void doInBackground(Void... params) {
HttpGet request = new HttpGet(url);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
response= mClient.execute(request, responseHandler);
} catch (ClientProtocolException exception) {
exception.printStackTrace();
return null;
} catch (IOException exception) {
exception.printStackTrace();
return null;
}
Log.i("routes",""+response);
jsonstr=response;
if(jsonstr!= null){
try{
/*JSONArray jsonary=new JSONArray(jsonstr);
JSONArray bus_scheduleee=jsonary.getJSONArray("bus_schedule");*/
JSONObject jsonObj = new JSONObject(jsonstr);
JSONArray bus_schedule = jsonObj.getJSONArray("bus_schedule");
JSONArray bus_route = jsonObj.getJSONArray("bus_route");
for (int i = 0; i < bus_route.length(); i++) {
JSONObject c = bus_route.getJSONObject(i);
String journeydatefromjson=c.getString("serviceDate");
String busname=c.getString("amenities");
String fromplace_json=c.getString("startCityName");
String departtimejson=c.getString("departureTime");
String farefromjson=c.getString("fare");
String endCityNamejson=c.getString("endCityName");
String arrivalTimejson=c.getString("arrivalTime");
String operatorNamejson=c.getString("operatorName");
String bus_idjson=c.getString("bus_id");
String journeyHoursjson=c.getString("journeyHours");
String available_seatjson=c.getString("available_seat");
String total_seatsjson=c.getString("total_seats");
String seat_typejson=c.getString("journeyHours");
Log.d("busdetails",""+journeydatefromjson+busname);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}`
Try use Gson lib for parse it.
dependencies {
compile 'com.google.code.gson:gson:2.3.1'
}
You can generation pojo for parse json. (For example on this site http://www.jsonschema2pojo.org)
For parse use this.
T t = new Gson().fromJson(serverResponse.getResponse(), type);
Where 'T' is your response data, and 'type' it pojo from site.
If your type is entity use Type type = Entity.class;
If your type is list of entities use
Type type = new TypeToken<List<WadadayFull>>() {
}.getType())
try this code:
try {
JSONArray array1 = new JSONArray(str);
for (int i=0;i<array1.length();i++){
JSONObject obj1 = array1.getJSONObject(i) ;
JSONArray array2 = obj1.getJSONArray("bus_schedule");
for (int j=0;j<array2.length();j++){
JSONObject obj2 = array2.getJSONObject(j);
JSONArray array3 = obj2.getJSONArray("bus_route");
ArrayList<Example1> list = new ArrayList<>();
for (int k=0;k<array3.length();k++) {
JSONObject obj3 = array3.getJSONObject(k);
String s1 = obj3.getString("serviceDate");
String s2 = obj3.getString("amenities");
String s3 = obj3.getString("startCityName");
String s4 = obj3.getString("departureTime");
String s5 = obj3.getString("fare");
String s6 = obj3.getString("endCityName");
String s7 = obj3.getString("arrivalTime");
String s8 = obj3.getString("operatorName");
String s9 = obj3.getString("bus_id");
String s10 = obj3.getString("journeyHours");
String s11 = obj3.getString("available_seat");
String s12 = obj3.getString("total_seats");
String s13 = obj3.getString("seat_type");
Example1 ex1 = new Example1();
ex1.setServiceDate(s1);
ex1.setAmenities(s2);
ex1.setStartCityName(s3);
list.add(ex1);
Log.e("response", list.toString());
}
JSONArray array4 = obj2.getJSONArray("boardingPoint");
ArrayList<Example2> list2 = new ArrayList<>();
for (int l = 0; l < array4.length(); l++) {
JSONObject obj4 = array4.getJSONObject(l);
String s14 = obj4.getString("boardingPointName");
String s15 = obj4.getString("boardingPointContact");
String s16 = obj4.getString("boardingPointTime");
String s17 = obj4.getString("boardingPointId");
String s18 = obj4.getString("BusId");
Example2 ex2 = new Example2();
ex2.setBoardingPointName(s14);
ex2.setBoardingPointContact(s15);
list2.add(ex2);
Log.e("response", list2.toString());
}
}
}
Log.e("response",array1.toString());
} catch (JSONException e) {
e.printStackTrace();
}
I'm trying to get JSON value by EditText.
At first I had a bunch of nullpointer exceptions, solved that. But now my function just isn't working. Been wrapping my brain over this...
I tried to create a EditText, get that value to a String, and get it over to the JSON Object. Don't know what I'm doing wrong... Or am I forgetting something?
public class MyActivity extends Activity {
TextView uid;
TextView name1;
TextView email1;
EditText edt;
Button Btngetdata;
//URL to get JSON Array
private static String url = "*";
//JSON Node Names
private static final String TAG_TAG = "tag";
private static final String TAG_ID = "id";
private static final String TAG_LAST_NAME = "last_name";
private static final String TAG_EMAIL = "country";
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Btngetdata = (Button)findViewById(R.id.getdata);
edt = (EditText)findViewById(R.id.edittext);
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();
uid = (TextView)findViewById(R.id.uid);
name1 = (TextView)findViewById(R.id.name);
email1 = (TextView)findViewById(R.id.email);
pDialog = new ProgressDialog(MyActivity.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
user = json.getJSONArray(TAG_TAG);
JSONObject c = user.getJSONObject(0);
String xyz = edt.getText().toString();
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_LAST_NAME);
String email = c.getString(TAG_EMAIL);
//Set JSON Data in TextView
uid.setText(id);
name1.setText(name);
email1.setText(email);
edt.setText(xyz);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
{"tag":[{"id":"1","first_name":"Philip","last_name":"Porter","email":"pporter0#admin.ch","country":"China","ip_address":"26.83.255.206"},{"id":"2","first_name":"Nancy","last_name":"Martin","email":"nmartin1#google.ca","country":"Colombia","ip_address":"160.93.80.1"},{"id":"3","first_name":"Ann","last_name":"Peterson","email":"apeterson2#utexas.edu","country":"China","ip_address":"251.254.74.162"},{"id":"4","first_name":"Rachel","last_name":"Clark","email":"rclark3#mayoclinic.com","country":"Brazil","ip_address":"58.218.248.5"},{"id":"5","first_name":"Heather","last_name":"Burton","email":"hburton4#creativecommons.org","country":"Ethiopia","ip_address":"244.69.119.16"},{"id":"6","first_name":"Ruth","last_name":"Lane","email":"rlane5#va.gov","country":"Brazil","ip_address":"18.173.102.54"},{"id":"7","first_name":"Andrew","last_name":"Turner","email":"aturner6#devhub.com","country":"United States","ip_address":"13.119.240.234"},{"id":"8","first_name":"Wanda","last_name":"Medina","email":"wmedina7#pagesperso-orange.fr","country":"Netherlands","ip_address":"151.139.21.237"},{"id":"9","first_name":"Robert","last_name":"Elliott","email":"relliott8#joomla.org","country":"United States","ip_address":"34.200.249.109"},{"id":"10","first_name":"Kevin","last_name":"Harrison","email":"kharrison9#nih.gov","country":"Brazil","ip_address":"106.84.164.86"}]}
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;
}
}
EDIT
JSONObject c = user.getJSONObject(Integer.parseInt(xyz));
I Modified to this, im getting a response other than default 1 when base value was getJSONObject(0), but now im entering 1 and im getting 2, entering 4 getting 5..
Does anyone know how to solve this one?
If you are trying to parse the whole json array then use this.In you post execute
List<String> allid = new ArrayList<String>();
JSONArray obj= jsonResponse.getJSONArray("tag");
for (int i=0; i<obj.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String id= actor.getString("id");
allNames.add(id);
}
Then you can use a for loop to get the id in the list accordingly.
Otherwise you can do this parsing Using the Gson Library(you can download Gson library here
Just create a class in your package
public class DetailArray {
public boolean status;
public List<Detail_User> details;
public class Detail_User {
public String id;
public String first_name;
public String last_name;
public String email;
public String country;
}
}
In your post execute
Where response is the json response
DetailArray detail1 = (new Gson()).fromJson(response.toString(),
DetailArray.class);
Now Suppose , if you want to set the names in a list view then
//return a arraylist
private ArrayList<String> getName(DetailArray detail) {
ArrayList name = new ArrayList<String>();
for (int i=0;i< detail.details.size();i++) {
name.add(splitStr[i]);
}
return names;
}
Setting the array adapter and setting it to a list
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
getName(detail);
listview.setAdapter(arrayAdapter);
For a particular position try like this
int positionToShow = Integer.parseInt(edt.getText().toString()) - 1;
user = json.getJSONArray(TAG_TAG);
for(int i = 0; i < user.length(); i++) {
if(positionToShow == i) {
JSONObject c = user.getJSONObject(i);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_LAST_NAME);
String email = c.getString(TAG_EMAIL);
uid.setText(id);
name1.setText(name);
email1.setText(email);
}
}
i've parse your json ...acc to number entered ..and it shows exact result....refer this....
final EditText no=(EditText)findViewById(R.id.editText1);
final Button click=(Button)findViewById(R.id.button1);
click.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
try
{
Toast.makeText(MainActivity.this, no.getText().toString(), 0).show();
HttpClient client=new DefaultHttpClient();
HttpGet request=new HttpGet("http://192.168.0.30/test.js");
HttpResponse response=client.execute(request);
HttpEntity entity=response.getEntity();
String json=EntityUtils.toString(entity);
JSONObject j1=new JSONObject(json);
JSONArray ja1=j1.getJSONArray("tag");
JSONObject j2=ja1.getJSONObject(Integer.parseInt(no.getText().toString())-1);
Toast.makeText(MainActivity.this, j2.getString("first_name").toString() , 0).show();
entity.consumeContent();
}
catch(Exception e)
{
e.getStackTrace();
Toast.makeText(MainActivity.this, e.toString() , 0).show();
}
}
});
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");
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
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...