標籤:android style blog http io color ar os sp
在Android用戶端與伺服器互動的過程中,用戶端一般採用json解析伺服器的返回資料。此時有兩種資料格式。但其根本都是字串或字串數組!
1、JSONObject
下面是PHP端代碼:
<?php$array = array( ‘username‘=>‘lhh‘, ‘password‘=>‘123456‘, ‘user_id‘=>‘1‘);echo json_encode($array);?>
我們這裡只是類比,所以,在沒有伺服器的情況下,也可以在java代碼中定義,如下:
String strJson = "{"username":"lhh","password":"123456","user_id":"1"}";
下面是android代碼:
//by 不剃頭的一休哥 2014//11/15package com.example.jsonjs;import java.io.BufferedReader;import java.io.InputStreamReader;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.json.JSONObject;import android.app.Activity;import android.os.Bundle;import android.os.Looper;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);new Thread(new Runnable(){@Overridepublic void run() {Looper.prepare();// TODO Auto-generated method stubHttpClient client = new DefaultHttpClient(); StringBuilder builder = new StringBuilder(); //地址根據實際情況而定 HttpGet myget = new HttpGet("http://192.168.1.104/login.php"); try { HttpResponse response = client.execute(myget); BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); for (String s = reader.readLine(); s != null; s = reader.readLine()) { builder.append(s); } //轉化為JSONObject JSONObject jsonObject = new JSONObject(builder.toString()); String re_username = jsonObject.getString("username"); String re_password = jsonObject.getString("password"); //setTitle("使用者id_"+re_user_id); Log.v("url response", "true="+re_username); Log.v("url response", "true="+re_password); //tv1.setText(re_username); //tv2.setText(re_password); //Toast.makeText(getApplicationContext(), re_username, Toast.LENGTH_LONG).show(); } catch (Exception e) { Log.v("url response", "false"); // Toast.makeText(getApplicationContext(), "false", Toast.LENGTH_LONG).show(); e.printStackTrace(); } Looper.loop();}}).start();}}
該代碼需要伺服器,如果是在java定義的json資料。
2、JSONArray
下面是PHP代碼(我用到了資料庫)
<?php$link=mysql_connect("localhost","username","password");mysql_query("SET NAMES utf8");mysql_select_db("test",$link);$sql=mysql_query("select * from teacher ",$link);while($row=mysql_fetch_assoc($sql)) $output[]=$row;echo json_encode($output);mysql_close();?>
當然也可以仿照上述在java代碼中定義,如下:
String strJson = "[{"id":"1","name":"wang"},{"id":"2","name":"liu"}]";
下面是android代碼:
//by 不剃頭的一休哥 2014/11/15package com.example.jsonjsarr;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.nio.charset.Charset;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import android.app.Activity;import android.os.Bundle;import android.os.Looper;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubLooper.prepare();getServerJsonDataWithTypes();Looper.loop();}}).start();}private void getServerJsonDataWithTypes() {// TODO Auto-generated method stubint res = 0;HttpClient client = new DefaultHttpClient();StringBuilder str = new StringBuilder();//此處地址根據實際情況而定HttpGet httpGet = new HttpGet("http://192.168.1.104/login.php");try{HttpResponse httpRes = client.execute(httpGet);res = httpRes.getStatusLine().getStatusCode();if(res == 200){BufferedReader buffer = new BufferedReader(new InputStreamReader(httpRes.getEntity().getContent()));String s = buffer.readLine();for(;s!=null;s=buffer.readLine()){str.append(s);}//字串轉化為JSONArrayJSONArray json = new JSONArray(str.toString());String strs=" ";for(int i = 0;i<json.length();i++){//按照下標進行訪問JSONObject jsonobject = (JSONObject)json.opt(i);strs += jsonobject.getString("name");}Toast.makeText(getApplicationContext(), strs, Toast.LENGTH_LONG).show();}else{Toast.makeText(getApplicationContext(), "httperror", Toast.LENGTH_LONG).show();}}catch(Exception e){Log.v("test", "exception");}}}
綜上兩種可以看出,其本質都是一樣,一個JSONArray分成多個JSONObject進行操作。
順便說下:
1、在Android 4.X中,進行網路訪問時不要放在主線程裡,否則APP可能會強制退出。
2、注意UI線程與非UI線程的區別。
3、Looper.prepare()與Looper.loop()的作用。
4、需要網路訪問時,別忘了在mainfest裡添加許可權
<uses-permission android:name="android.permission.INTERNET"/>
5、小弟不才,如有錯誤,還請指出。
6、代碼雖然是我寫的,但是有問題盡量不要找我,是他自己長歪了。
7、轉載請註明出處。
Android 解析JSONObject以及JSONArray對比