Home>
package com.practice.json;
import org.json.jsonarray;
import org.json.jsonexception;
import org.json.jsonobject;
import android.app.activity;
import android.os.bundle;
import android.util.log;
public class jsondemo extends activity {
 /*
  * Example of parsing json, str stores json code, and the parsed data is output in logcat
 * /
 string tag="json message";
 @override
 public void oncreate (bundle savedinstancestate) {
  super.oncreate (savedinstancestate);
  setcontentview (r.layout.main);
  detectjson ();
 }
 private void detectjson () {
  string str="{" +
   "\" Date \ ":\" 2011-06-06 \ "," +
   //like is jsonobject
   "\" like \ ":{" +
   "\" name \ ":\" Garnett \ "," +
   "\" height \ ":\" 2.11cm \ "," +
   "\" age \ ":35" +
   "}," +
   //likelist is a jsonobject
   "\" likelist \ ":" +
    "{\" list \ ":" +
    "[" +
     //here is also jsonobject
     "{" +
     "\" name \ ":\" rose \ "," +
     "\" height \ ":\" 190cm \ "," +
     "\" age \ ":23" +
     "}," +
     //here is also jsonobject
     "{" +
     "\" name \ ":\" Kobe \ "," +
     "\" height \ ":\" 198cm \ "," +
     "\" age \ ":33" +
     "}" +
    "]" +
    "}" +
   "}";
  try {
   jsonobject datajson=new jsonobject (str);
   log.d (tag, datajson.getstring ("date"));
   jsonobject nbajson=datajson.getjsonobject ("like");
   log.d (tag, nbajson.getstring ("name"));
   log.d (tag, nbajson.getstring ("height"));
   log.d (tag, nbajson.get ("age"). tostring ());
   jsonobject listjson=datajson.getjsonobject ("likelist");
   jsonarray arrayjson=listjson.getjsonarray ("list");
   for (int i=0;i<arrayjson.length ();i ++) {
    jsonobject tempjson=arrayjson.optjsonobject (i);
    log.d (tag, tempjson.getstring ("name"));
    log.d (tag, tempjson.getstring ("height"));
    log.d (tag, tempjson.getstring ("age"). tostring ());
   }
  } catch (jsonexception e) {
   system.out.println ("something wrong ...");
   e.printstacktrace ();
  }
 }
}
  • Previous Interlacing text with JavaScript and CSS
  • Next Talk about the realization process of Ajax principle