The example in this article describes how Android realizes reading and writing JSON data. Share to everyone for your reference. Specifically as follows:
1. Parse JSON:
Package De.vogella.android.twitter.json;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import Org.apache.http.StatusLine;
Import org.apache.http.client.ClientProtocolException;
Import org.apache.http.client.HttpClient;
Import Org.apache.http.client.methods.HttpGet;
Import org.apache.http.impl.client.DefaultHttpClient;
Import Org.json.JSONArray;
Import Org.json.JSONObject;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.util.Log; The public class Parsejson extends activity {/** called the ' when the ' is the ' The activity ' is a./@Override public void created
Ate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
String readtwitterfeed = Readtwitterfeed ();
try {jsonarray Jsonarray = new Jsonarray (readtwitterfeed); LOG.I (ParseJSON.class.getName (), "number of entries"+ jsonarray.length ());
for (int i = 0; i < jsonarray.length (); i++) {Jsonobject jsonobject = Jsonarray.getjsonobject (i);
LOG.I (ParseJSON.class.getName (), jsonobject.getstring ("text"));
} catch (Exception e) {e.printstacktrace ();
} public String Readtwitterfeed () {StringBuilder builder = new StringBuilder ();
HttpClient client = new Defaulthttpclient ();
HttpGet httpget = new HttpGet ("Http://twitter.com/statuses/user_timeline/vogella.json");
try {httpresponse response = Client.execute (HttpGet);
Statusline statusline = Response.getstatusline ();
int statusCode = Statusline.getstatuscode ();
if (StatusCode = =) {httpentity entity = response.getentity ();
InputStream content = Entity.getcontent ();
BufferedReader reader = new BufferedReader (new InputStreamReader (content));
String Line;
while (line = Reader.readline ())!= null) {builder.append (line); } else {LOG.E (ParseJSON.class.toStrING (), "Failed to download File");
} catch (Clientprotocolexception e) {e.printstacktrace ();
catch (IOException e) {e.printstacktrace ();
return builder.tostring ();
}
}
2. Generate JSON:
public void Writejson () {
Jsonobject object = new Jsonobject ();
try {
object.put ("name", "Jack Hack");
Object.put ("Score", new Integer);
Object.put ("Current", New Double (152.32));
Object.put ("nickname", "Hacker");
} catch (Jsonexception e) {
e.printstacktrace ();
}
System.out.println (object);
I hope this article will help you with your Android program.