How to parse JSON in Android -
where can find step-by-step instructions on how parse json feed in android? i'm android beginner wanting learn.
android has tools need parse json built-in. example follows, no need gson or that.
get json:
defaulthttpclient httpclient = new defaulthttpclient(new basichttpparams()); httppost httppost = new httppost(http://somejsonurl/jsonwebservice); // depends on web service httppost.setheader("content-type", "application/json"); inputstream inputstream = null; string result = null; try { httpresponse response = httpclient.execute(httppost); httpentity entity = response.getentity(); inputstream = entity.getcontent(); // json utf-8 default bufferedreader reader = new bufferedreader(new inputstreamreader(inputstream, "utf-8"), 8); stringbuilder sb = new stringbuilder(); string line = null; while ((line = reader.readline()) != null) { sb.append(line + "\n"); } result = sb.tostring(); } catch (exception e) { // oops } { try{if(inputstream != null)inputstream.close();}catch(exception squish){} }
now have json, what?
create jsonobject:
jsonobject jobject = new jsonobject(result);
to specific string
string ajsonstring = jobject.getstring("stringname");
to specific boolean
boolean ajsonboolean = jobject.getboolean("booleanname");
to specific integer
int ajsoninteger = jobject.getint("integername");
to specific long
long ajsonlong = jobject.getboolean("longname");
to specific double
double ajsondouble = jobject.getdouble("doublename");
to specific jsonarray:
jsonarray jarray = jobject.getjsonarray("arrayname");
to items array
for (int i=0; < jarray.length(); i++) { try { jsonobject oneobject = jarray.getjsonobject(i); // pulling items array string oneobjectsitem = oneobject.getstring("stringnameinthearray"); string oneobjectsitem2 = oneobject.getstring("anotherstringnameinthearray"); } catch (jsonexception e) { // oops } }
Comments
Post a Comment