Android使用JSON與服務器交互


1.JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式。 易於人閱讀和編寫。同時也易於機器解析和生成。 它基於JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一個子集。 JSON采用完全獨立於語言的文本格式,但是也使用了類似於C語言家族的習慣(包括C, C++, C#, Java, JavaScript, Perl, Python等)。 這些特性使JSON成為理想的數據交換語言。

 

JSON具有以下這些形式:

 

對象是一個無序的“‘名稱/值’對”集合。一個對象以“{”(左括號)開始,“}”(右括號)結束。每個“名稱”后跟一個“:”(冒號);“‘名稱/值’ 對”之間使用“,”(逗號)分隔。

 

2.需要的類包:

  org.json.package,JSONObject

  org.apache.http.package,DefaultHttpClient

 

3.服務器端,我們使用grails提供數據服務,數據庫使用mysql,以其中一張表Person(name,gender,title)為例,在Controller中提供person列表服務,其格式為JSON

 

  def index() {
        def parg=params
        if(params.data){
          //如果存在data參數,將該參數轉換為JSONObject
          JSONObject json=new JSONObject(params.data)
def sqlinsert=new Sql(dataSource)
           //從JSONObject中獲取數據並插入數據庫 sqlinsert.executeInsert(
" INSERT INTO person (name,gender,title) values (?,?,?)", [json.getString("name"),json.getString("gender"),json.getString("title")]) } def sql= new Sql(dataSource)
       //獲取Person列表,以JSON方式返回 def rows
=sql.rows("select name,gender,title from person") sql.close() render rows as JSON }

 

4 Android端

4.1從服務器端獲取數據並顯示

    public void doHttpGetJSON(View view) throws IOException, JSONException {
        
        DefaultHttpClient httpClient = new DefaultHttpClient();
        //指定服務器端URL
        HttpGet get = new HttpGet("http://10.4.30.228:8080/PersonForAndroid/person");
        HttpResponse rsp = httpClient.execute(get);
        //獲取響應的實體
        HttpEntity httpEntity = rsp.getEntity();
        //將響應的實體轉換為字符串
        String jsonString = EntityUtils.toString(httpEntity);
        //服務器端返回的數據格式為:[{"name":"Johnny","gender":"Male","title":"Programmer"},{"name":"Kevin","gender":"Male","title":"Manager"}]
        //是一個JSON數組,因此使用JSONArray將字符串轉換為JSONArray
        //如果服務器端返回的是JSON字符串:{"name":"Johnny","gender":"Male","title":"Programmer"},則使用JSONObject jsonObject=new JSONObject(jsonString);
        JSONArray jsonArray=new JSONArray(jsonString);
        String resultsString="";
        //遍歷JSONArray,將結果輸出
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            String name = jsonObj.getString("name");
            String gender = jsonObj.getString("gender");
            String title = jsonObj.getString("title");
            resultsString += title + " " + name + " is " + gender+"\r\n";
        }
        TextView getTextView = (TextView) findViewById(R.id.jsonGetTextView);
        getTextView.setText(resultsString);
    }

4.2向服務器提交JSON格式數據

 

    public void doHttpPostJSON(View view) throws IOException, JSONException {
        //定義一個JSON,用於向服務器提交數據
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("name", getTextFromView(R.id.name))
                .put("gender", getTextFromView(R.id.gender))
                .put("title", getTextFromView(R.id.title));
        String jsonString = jsonObj.toString();
        //指定Post參數
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("data", jsonString));
        
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://10.4.30.228:8080/PersonForAndroid/person");
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse rsp = httpClient.execute(post);
        
        HttpEntity httpEntity = rsp.getEntity();
        String displayString = EntityUtils.toString(httpEntity);
        
        TextView getTextView = (TextView) findViewById(R.id.jsonPostTextView);
        getTextView.setText(displayString);
    }

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM