JSON入门介绍:
也参考了此篇:
json数据格式解析我自己分为两种:一种是普通的,一种是带有数组形式的:
先实例化个JSONObject对象
JSONObject aJosnObj = new JSONObject(jsonStr);//jsonStr为对应json字符串数据然后再根据json数据的实际情况调用有关方法。这是一个利用JSON定位的例子:
/** * Google定位的实现.<br/> * Geolocation的详细信息请参见:<br/> * <a * href="http://code.google.com/apis/gears/geolocation_network_protocol.html" mce_href="http://code.google.com/apis/gears/geolocation_network_protocol.html"> * http://code.google.com/apis/gears/geolocation_network_protocol.html</a> */ public class LocationAct extends Activity { private TextView txtInfo; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btn = (Button) findViewById(R.id.btnStart); txtInfo = (TextView) findViewById(R.id.txtInfo); btn.setOnClickListener(new Button.OnClickListener() { public void onClick(View view) { getLocation(); } }); } private void getLocation() { TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); GsmCellLocation gsmCell = (GsmCellLocation) tm.getCellLocation(); int cid = gsmCell.getCid(); int lac = gsmCell.getLac(); String netOperator = tm.getNetworkOperator(); int mcc = Integer.valueOf(netOperator.substring(0, 3)); int mnc = Integer.valueOf(netOperator.substring(3, 5)); JSONObject holder = new JSONObject(); JSONArray array = new JSONArray(); JSONObject data = new JSONObject(); try { holder.put("version", "1.1.0"); holder.put("host", "maps.google.com"); holder.put("address_language", "zh_CN"); holder.put("request_address", true); holder.put("radio_type", "gsm"); holder.put("carrier", "HTC"); data.put("cell_id", cid); data.put("location_area_code", lac); data.put("mobile_countyr_code", mcc); data.put("mobile_network_code", mnc); array.put(data); holder.put("cell_towers", array); } catch (JSONException e) { e.printStackTrace(); } DefaultHttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://www.google.com/loc/json"); StringEntity stringEntity = null; try { stringEntity = new StringEntity(holder.toString()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } httpPost.setEntity(stringEntity); HttpResponse httpResponse = null; try { httpResponse = client.execute(httpPost); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } HttpEntity httpEntity = httpResponse.getEntity(); InputStream is = null; try { is = httpEntity.getContent(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } InputStreamReader isr = new InputStreamReader(is); BufferedReader reader = new BufferedReader(isr); StringBuffer stringBuffer = new StringBuffer(); try { String result = ""; while ((result = reader.readLine()) != null) { stringBuffer.append(result); } } catch (IOException e) { e.printStackTrace(); } txtInfo.setText(stringBuffer.toString()); } }