欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android实现读写JSON数据的方法

程序员文章站 2024-02-10 11:39:52
本文实例讲述了android实现读写json数据的方法。分享给大家供大家参考。具体如下: 1. 解析json: package de.vogella.andro...

本文实例讲述了android实现读写json数据的方法。分享给大家供大家参考。具体如下:

1. 解析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;
public class parsejson extends activity {
 /** called when the activity is first created. */
 @override
 public void oncreate(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 == 200) {
    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. 生成json:

public void writejson() {
 jsonobject object = new jsonobject();
 try {
  object.put("name", "jack hack");
  object.put("score", new integer(200));
  object.put("current", new double(152.32));
  object.put("nickname", "hacker");
 } catch (jsonexception e) {
  e.printstacktrace();
 }
 system.out.println(object);
}

希望本文所述对大家的android程序设计有所帮助。