Adroid解析json
参考资料:
http://www.open-open.com/lib/view/open1326376799874.html
http://www.cnblogs.com/tt_mc/archive/2011/01/04/1925327.html
总结:
解析普通json:使用JSONObject,getString方法;
解析数组形式json:使用JSONArray,getJSONArray方法后,遍历数组,使用普通json的解析方法;
public class GetPostMain extends Activity { Button get , post; EditText show; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); get = (Button) findViewById(R.id.get); post = (Button) findViewById(R.id.post); show = (EditText)findViewById(R.id.show); get.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String response = GetPostUtil .sendGet("http://www.weather.com.cn/data/sk/101281601.html" , null); show.setText(response); } }); post.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String data = "";
try{
// 构造json
JSONObject param = new JSONObject();
param.put("userid", "uid45798");
param.put("lat", "32.038587000000");
param.put("lon", "118.778906000000");
data = param.toString();
}catch(JSONException e){
Log.e("postdata", "Json post error");
}
String response = GetPostUtil.sendPost("http://xxxx.getNearbyActivity", data);
Log.d("postdata",data);
String str1 = ""; String str2 = ""; try{ // 获取单个key值 JSONObject jsonObj = new JSONObject(response.toString()); String errorcode = "errorcode:" + jsonObj.getString("errorcode"); String count = "count:" + jsonObj.getString("count"); String userid = "userid:" + jsonObj.getString("userid"); str1 = errorcode+"\n"+userid+"\n"+count+"\n"; }catch(JSONException e){ System.out.println("Json parse error"); str1 = "str1没有数据\n"; } try{ // 获取多组json JSONArray jsonObjs = new JSONObject(response.toString()).getJSONArray("datalist"); for(int i = 0; i < jsonObjs.length() ; i++){ JSONObject jsonObj = (JSONObject)jsonObjs.opt(i); String brand = "brand:"+ jsonObj.getString("brand"); String aid = "aid:"+ jsonObj.getString("aid"); str2 += aid+","+brand+"\n"; } }catch(JSONException e){ System.out.println("Json parse error"); str2 = "str2没有数据"; } show.setText(str1+str2); } }); } }