业务逻辑类:
package com.example.mytool;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.content.Context;
public class mjson {
private Context context;
public mjson(Context context) {
this.context = context;
}
/*
* 简单读取json对象
*
* */
public String readjson(String str) throws Exception{
String result=str;
JSONObject oj=new JSONObject(result);
int id=oj.getInt("id");
String name=oj.getString("title");
String re="编号:"+id+" 名字:"+name+"";
return re;
}
/*
* 读取复杂json数据
* */
public String readjsons() throws Exception{
String result="[{id:1,'name':'liyihang'},{'id':2,'name':'xieqiping'}]";
JSONArray ojs=new JSONArray(result);
String str="";
for(int i=0; i<ojs.length(); i++){
JSONObject oj=((JSONObject)ojs.opt(i));
int id=oj.getInt("id");
String name=oj.getString("name");
str+="id:"+id+" name:"+name+"";
}
return str;
}
/*
* 生成json对象
* */
public JSONObject shengcheng() throws Exception{
JSONObject jobj=new JSONObject();
JSONArray phone=new JSONArray();
phone.put(123456).put(789);
jobj.put("phone", phone);
jobj.put("name", "liyihang");
jobj.put("age", 18);
JSONObject address=new JSONObject();
address.put("jieli", "chenzhou");
address.put("city", "changsha");
jobj.put("address", address);
jobj.put("islogin", true);
return jobj;
}
}