Android JSON資料的解析與封裝小Demo

來源:互聯網
上載者:User

標籤:android   json   解析   demo   

今天早早的下班了,寫了一個簡單的JSON Demo,這裡總結一下。

首先是:


簡單起見,解析部分並沒有採用解析URL的方式,直接把JSON寫到String裡,邏輯比較簡單,這裡就不囉嗦了,上代碼:

package com.example.jsondemo;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import android.app.Activity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;public class Main extends Activity {// private static final String BASE_URL =// "http://zhoumushui.sinaapp.com/json/";private TextView tvMsg;private TextView tvJson;private EditText etName;private EditText etAge;private String strJson = "";private String staffInfo = "";private String strJsonRes = "";private String strMsg;private Button btnAdd;private Button btnJson;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);tvMsg = (TextView) findViewById(R.id.tvMsg);tvJson = (TextView) findViewById(R.id.tvJson);etName = (EditText) findViewById(R.id.etName);etAge = (EditText) findViewById(R.id.etAge);btnAdd = (Button) findViewById(R.id.btnAdd);btnJson = (Button) findViewById(R.id.btnJson);MsgToJson(); // 封裝JsonJsonToMsg(); // 解析Json}class onClickListenerImp implements OnClickListener {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubif (v == btnAdd) {if (strMsg != null && strJson.trim().length() != 0) {strMsg = strMsg + ",{name:'" + etName.getText().toString()+ "',age:" + etAge.getText().toString() + "}";} else {strMsg = "{staff:[{name:'" + etName.getText().toString()+ "',age:" + etAge.getText().toString() + "}";}Toast.makeText(Main.this, "Add Succcess!", Toast.LENGTH_SHORT).show();etAge.setText("");etName.setText("");} else if (v == btnJson) {strJsonRes = "";strJsonRes = strMsg + "]}";tvJson.setText(strJsonRes);}}}private void MsgToJson() {btnAdd.setOnClickListener(new onClickListenerImp());btnJson.setOnClickListener(new onClickListenerImp());}private void JsonToMsg() {strJson = "{staff:[{name:'Alex',age:21},{name:'Zhou',age:22},{name:'Anne',age:23}],company:'T-Chip'}";staffInfo = "未經處理資料:\n" + strJson + "\n\n解析之後:\n";try {JSONObject mJsonObject = new JSONObject(strJson);JSONArray mJsonArray = mJsonObject.getJSONArray("staff");String company = mJsonObject.getString("company");staffInfo = staffInfo + company + "共有 " + mJsonArray.length()+ " 個員工,資訊如下:\n";for (int staffCount = 0; staffCount < mJsonArray.length(); staffCount++) {// 擷取員工JSONObject staff = mJsonArray.getJSONObject(staffCount);int staffNo = staffCount + 1;staffInfo = staffInfo + "序號:" + staffNo + "  姓名: "+ staff.getString("name") + "  年齡: "+ staff.getInt("age") + "\n";}tvMsg.setText(staffInfo);} catch (JSONException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}}


布局有點拖遝,其實資料封裝部分還可以利用一下解析部分的邏輯。

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView        android:id="@+id/tvMsg"        android:layout_width="fill_parent"        android:layout_height="wrap_content" />    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="==========================" />    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:orientation="horizontal" >        <EditText            android:id="@+id/etName"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:hint="姓名" />        <EditText            android:id="@+id/etAge"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:hint="年齡" />        <Button            android:id="@+id/btnAdd"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="增加" />          <Button            android:id="@+id/btnJson"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="JSON" />            </LinearLayout>    <TextView        android:id="@+id/tvJson"        android:layout_width="fill_parent"        android:layout_height="wrap_content" /></LinearLayout>


轉載請註明出處:周木水的CSDN部落格 http://blog.csdn.net/zhoumushui

我的GitHub:周木水的GitHub https://github.com/zhoumushui


Android JSON資料的解析與封裝小Demo

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.