当前位置: 移动技术网 > 移动技术>移动开发>Android > Android实现读写JSON数据的方法

Android实现读写JSON数据的方法

2019年07月24日  | 移动技术网移动技术  | 我要评论

本文实例讲述了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程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网