1. 程式人生 > >android 將資料轉換成JSON資料格式並使用JSONObject解析JSON格式的資料

android 將資料轉換成JSON資料格式並使用JSONObject解析JSON格式的資料

比起XML檔案解析,JSON資料解析的有點在於他的體積小,在網路上傳輸的時候可以更省流量。同時它也有缺點,Json資料的語義性較差,看起來沒有XML直觀。現在JSON已經被大多數開發人員所接受,在網路資料的傳輸當中應用非常廣泛。現在做的專案需要把資料轉換成下面的格式:

 {"PatitentData":[{"patient_mhistory":"高血壓","patient_insomnia":"六個月","patient_gender":"男","patient_name":"張三","current_date":"2015.4.10","patient_phone":"1243543546","patient_scde":"大學本科","patient_age":"56","patient_postion":"農民"}],"sleepDiary":[{"day07":"1243535","day06":"12324343","day05":"1243434","day04":"2435434521","day01":"121422343","day02":"1231421454","day03":"1243243"}],"testData":[{"isi":"12324324","hama":"122543543","hamd":"2334255","sleepness":"1243345432","pqsi":"124332144452"}]}

首先建立 PatientInformation.java、PatientTest.java和SleepDiary這三個類,主要是用來封裝一些資訊

PatientInformation.java

package com.zghaikun.json;

public class PatientInformation {
	private int id;
	private String patient_name;
	private String patient_gender;
	private String patient_age;
	private String patient_postion;
	private String patient_scde;
	private String patient_insomnia;
	private String patient_mhistory;
	private String patient_phone;
	private String current_date;
	private int patient_hamd;
	public PatientInformation() {
		super();
	}
	public PatientInformation(int patient_hamd) {
		super();
		this.patient_hamd = patient_hamd;
	}
	public PatientInformation( String current_date,String patient_name, String patient_gender,
			String patient_age, String patient_postion, String patient_scde,
			String patient_insomnia, String patient_mhistory,
			String patient_phone) {
		super();
		this.current_date = current_date;
		this.patient_name = patient_name;
		this.patient_gender = patient_gender;
		this.patient_age = patient_age;
		this.patient_postion = patient_postion;
		this.patient_scde = patient_scde;
		this.patient_insomnia = patient_insomnia;
		this.patient_mhistory = patient_mhistory;
		this.patient_phone = patient_phone;
		
	}
	public PatientInformation(int id, String current_date,String patient_name, String patient_gender,
			String patient_age, String patient_postion, String patient_scde,
			String patient_insomnia, String patient_mhistory,
			String patient_phone) {
		super();
		this.id = id;
		this.current_date = current_date;
		this.patient_name = patient_name;
		this.patient_gender = patient_gender;
		this.patient_age = patient_age;
		this.patient_postion = patient_postion;
		this.patient_scde = patient_scde;
		this.patient_insomnia = patient_insomnia;
		this.patient_mhistory = patient_mhistory;
		this.patient_phone = patient_phone;
		
	}
	public int getPatient_hamd() {
		return patient_hamd;
	}
	public void setPatient_hamd(int patient_hamd) {
		this.patient_hamd = patient_hamd;
	}
	public String getPatient_age() {
		return patient_age;
	}
	public void setPatient_age(String patient_age) {
		this.patient_age = patient_age;
	}
	public String getCurrentdate() {
		return current_date;
	}
	public void setCurrentdate(String currentdate) {
		this.current_date = currentdate;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getPatient_name() {
		return patient_name;
	}
	public void setPatient_name(String patient_name) {
		this.patient_name = patient_name;
	}
	public String getPatient_gender() {
		return patient_gender;
	}
	public void setPatient_gender(String patient_gender) {
		this.patient_gender = patient_gender;
	}
	public String getPatient_postion() {
		return patient_postion;
	}
	public void setPatient_postion(String patient_postion) {
		this.patient_postion = patient_postion;
	}
	public String getPatient_scde() {
		return patient_scde;
	}
	public void setPatient_scde(String patient_scde) {
		this.patient_scde = patient_scde;
	}
	public String getPatient_insomnia() {
		return patient_insomnia;
	}
	public void setPatient_insomnia(String patient_insomnia) {
		this.patient_insomnia = patient_insomnia;
	}
	public String getPatient_mhistory() {
		return patient_mhistory;
	}
	public void setPatient_mhistory(String patient_mhistory) {
		this.patient_mhistory = patient_mhistory;
	}
	public String getPatient_phone() {
		return patient_phone;
	}
	public void setPatient_phone(String patient_phone) {
		this.patient_phone = patient_phone;
	}
}
PatientTest.java
package com.zghaikun.json;

public class PatientTest {
	int id;
	String pqsi;
	String sleepness;
	String hama;
	String hamd;
	String isi;
	public String getIsi() {
		return isi;
	}
	public void setIsi(String isi) {
		this.isi = isi;
	}
	public PatientTest() {
		super();
	}
	public PatientTest(int id, String pqsi, String sleepness, String hama,
			String hamd,String isi) {
		super();
		this.id = id;
		this.pqsi = pqsi;
		this.sleepness = sleepness;
		this.hama = hama;
		this.hamd = hamd;
		this.isi = isi;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getPqsi() {
		return pqsi;
	}
	public void setPqsi(String pqsi) {
		this.pqsi = pqsi;
	}
	public String getSleepness() {
		return sleepness;
	}
	public void setSleepness(String sleepness) {
		this.sleepness = sleepness;
	}
	public String getHama() {
		return hama;
	}
	public void setHama(String hama) {
		this.hama = hama;
	}
	public String getHamd() {
		return hamd;
	}
	public void setHamd(String hamd) {
		this.hamd = hamd;
	}

}
SleepDiary.java
package com.zghaikun.json;

public class SleepDiary {
	private int id;
	private String day01;
	private String day02;
	private String day03;
	private String day04;
	private String day05;
	private String day06;
	private String day07;
	public SleepDiary(String day01, String day02, String day03, String day04,
			String day05, String day06, String day07) {
		super();
		this.day01 = day01;
		this.day02 = day02;
		this.day03 = day03;
		this.day04 = day04;
		this.day05 = day05;
		this.day06 = day06;
		this.day07 = day07;
	}
	public SleepDiary(int id, String day01, String day02, String day03,
			String day04, String day05, String day06, String day07) {
		super();
		this.id = id;
		this.day01 = day01;
		this.day02 = day02;
		this.day03 = day03;
		this.day04 = day04;
		this.day05 = day05;
		this.day06 = day06;
		this.day07 = day07;
	}
	public SleepDiary() {
		super();
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getDay01() {
		return day01;
	}
	public void setDay01(String day01) {
		this.day01 = day01;
	}
	public String getDay02() {
		return day02;
	}
	public void setDay02(String day02) {
		this.day02 = day02;
	}
	public String getDay03() {
		return day03;
	}
	public void setDay03(String day03) {
		this.day03 = day03;
	}
	public String getDay04() {
		return day04;
	}
	public void setDay04(String day04) {
		this.day04 = day04;
	}
	public String getDay05() {
		return day05;
	}
	public void setDay05(String day05) {
		this.day05 = day05;
	}
	public String getDay06() {
		return day06;
	}
	public void setDay06(String day06) {
		this.day06 = day06;
	}
	public String getDay07() {
		return day07;
	}
	public void setDay07(String day07) {
		this.day07 = day07;
	}
	
}
一個佈局檔案,由兩個按鍵和一個textView組成,
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
     >
	
   
    <Button
        android:id="@+id/bt2" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="把普通資料換成json資料格式的string"/>

    <Button
        android:id="@+id/bt4" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="解析帶集合的json字串"/>
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="30sp"
        android:text="@string/hello_world" />

</LinearLayout>
Mainactivity.java
package com.zghaikun.json;

import java.util.ArrayList;
import java.util.List;

import org.apache.axis2.AxisFault;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	private Button button1, button2, button3, button4;  //4個按鈕
	private TextView textView;  //顯示處理結果的textview
	private List<PatientInformation> patientInfos; //儲存資料的集合
	private List<PatientTest> patientTest;
	private List<SleepDiary> sleepDiarys;
	private JSONObject object;  //JSONObject物件,處理一個一個的物件
	private JSONObject objPatientInfo;
	private JSONObject objTestData;
	private JSONObject objSleepDiary;
	private JSONArray jsonArrayPatientInfo;//JSONObject物件,處理一個一個集合或者陣列
	private JSONArray jsonArrayTestData;//JSONObject物件,處理一個一個集合或者陣列
	private JSONArray jsonArraySleepDiary;//JSONObject物件,處理一個一個集合或者陣列
	private String jsonString;  //儲存帶集合的json字串
	private String jsonString2;//不帶集合的json字串
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
		initView(); //初始化控制元件
		initDate(); //初始化資料
		setListener(); //繫結監事件
		
		
//		try {
//			SimpleServiceStub stub  = new SimpleServiceStub();
//			SimpleServiceStub.GetGreeting gg = new SimpleServiceStub.GetGreeting();
//			gg.setParam0("比爾");
//			System.out.println(stub.getGreeting(gg).local_return);
//			System.out.println(stub.getPrice().local_return);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
	
	}
	private void initView() {
		// TODO Auto-generated method stub
		button2 = (Button) findViewById(R.id.bt2);
		button4 = (Button) findViewById(R.id.bt4);
		textView = (TextView) findViewById(R.id.text);
	}
    
	
	private void initDate() {
		//設定了兩個物件 
		patientInfos = new ArrayList<PatientInformation>();
		PatientInformation pateintInfo = new PatientInformation();
		pateintInfo.setPatient_name("張三");
		pateintInfo.setPatient_gender("男");
		pateintInfo.setPatient_age("56");
		pateintInfo.setPatient_postion("農民");
		pateintInfo.setPatient_scde("大學本科");
		pateintInfo.setPatient_insomnia("六個月");
		pateintInfo.setPatient_mhistory("高血壓");
		pateintInfo.setPatient_phone("1243543546");
		pateintInfo.setCurrentdate("2015.4.10");
		patientInfos.add(pateintInfo);
	 
		//測試資料
		patientTest = new ArrayList<PatientTest>();
		PatientTest PatienData = new PatientTest();
		PatienData.setPqsi("124332144452");
		PatienData.setSleepness("1243345432");
		PatienData.setHama("122543543");
		PatienData.setHamd("2334255");
		PatienData.setIsi("12324324");
		patientTest.add(PatienData);
		
		sleepDiarys = new ArrayList<SleepDiary>();
		SleepDiary sleepDiary = new SleepDiary();
		sleepDiary.setDay01("121422343");
		sleepDiary.setDay02("1231421454");
		sleepDiary.setDay03("1243243");
		sleepDiary.setDay04("2435434521");
		sleepDiary.setDay05("1243434");
		sleepDiary.setDay06("12324343");
		sleepDiary.setDay07("1243535");
		sleepDiarys.add(sleepDiary);
		
	}
//	//繫結監聽器
	private void setListener() {
		button2.setOnClickListener(this);
		button4.setOnClickListener(this);
		}
	 //把一個集合轉換成json格式的字串
	private void changeArrayDateToJson() { 
		jsonArrayPatientInfo = null;
		object = null;
		jsonArrayPatientInfo = new JSONArray();
		jsonArrayTestData = new JSONArray();
		jsonArraySleepDiary = new JSONArray();
		object = new JSONObject();
		//遍歷上面初始化的集合資料,把資料加入JSONObject裡面
		for (int i = 0; i < patientInfos.size(); i++) {  
			//一個user物件,使用一個JSONObject物件來裝
			objPatientInfo = new JSONObject();
		try {
			 //從集合取出資料,放入JSONObject裡面 JSONObject物件和map差不多用法,以鍵和值形式儲存資料
			objPatientInfo.put("patient_name", patientInfos.get(i).getPatient_name()); 
			objPatientInfo.put("patient_gender", patientInfos.get(i).getPatient_gender());
			objPatientInfo.put("patient_age", patientInfos.get(i).getPatient_age());
			objPatientInfo.put("patient_postion", patientInfos.get(i).getPatient_postion());
			objPatientInfo.put("patient_scde", patientInfos.get(i).getPatient_scde());
			objPatientInfo.put("patient_insomnia", patientInfos.get(i).getPatient_insomnia());
			objPatientInfo.put("patient_mhistory", patientInfos.get(i).getPatient_mhistory());
			objPatientInfo.put("patient_phone", patientInfos.get(i).getPatient_phone());
			objPatientInfo.put("current_date", patientInfos.get(i).getCurrentdate());
			
			//把JSONObject物件裝入jsonArray數組裡面
			jsonArrayPatientInfo.put(objPatientInfo); 
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		for(int i = 0 ; i < patientTest.size(); i++){
			//測試物件,使用JSONObject
			objTestData = new JSONObject();
			
			try {
				objTestData.put("pqsi", patientTest.get(i).getPqsi());
				objTestData.put("sleepness", patientTest.get(i).getSleepness());
				objTestData.put("hama", patientTest.get(i).getHama());
				objTestData.put("hamd", patientTest.get(i).getHamd());
				objTestData.put("isi", patientTest.get(i).getIsi());
				//把JSONObject物件裝入jsonArray數組裡面
				jsonArrayTestData.put(objTestData);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		for(int i = 0 ; i < sleepDiarys.size(); i++){
			//測試物件,使用JSONObject
			objSleepDiary = new JSONObject();
			
			try {
				objSleepDiary.put("day01", sleepDiarys.get(i).getDay01());
				objSleepDiary.put("day02", sleepDiarys.get(i).getDay02());
				objSleepDiary.put("day03", sleepDiarys.get(i).getDay03());
				objSleepDiary.put("day04", sleepDiarys.get(i).getDay04());
				objSleepDiary.put("day05", sleepDiarys.get(i).getDay05());
				objSleepDiary.put("day06", sleepDiarys.get(i).getDay06());
				objSleepDiary.put("day07", sleepDiarys.get(i).getDay07());
				//把JSONObject物件裝入jsonArray數組裡面
				jsonArraySleepDiary.put(objSleepDiary);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		 
		try {
			 //再把JSONArray資料加入JSONObject物件裡面(陣列也是物件)
			object.put("PatitentData", jsonArrayPatientInfo);
			object.put("testData", jsonArrayTestData);
			object.put("sleepDiary", jsonArraySleepDiary);
			//object.put("time", "2013-11-14"); //這裡還可以加入資料,這樣json型字串,就既有集合,又有普通資料
			} catch (JSONException e) {
				e.printStackTrace();
			}
			jsonString = null;
			//把JSONObject轉換成json格式的字串
			jsonString  = object.toString(); 
			textView.setText(jsonString);
			Log.i("輸出json字串", "轉換成json字串: " + jsonString);
		 
		}
		@Override
	public void onClick(View v) {
		switch (v.getId()) {
		 
		case R.id.bt2:
			changeArrayDateToJson(); //點選第2個按鈕,把普通資料換成json資料格式的string
			break;
		case R.id.bt4://解析帶集合的json字串
			if (jsonString==null || "".equals(jsonString)) {
				Toast.makeText(MainActivity.this, "請先點選第2按鈕把資料換成json字串", Toast.LENGTH_LONG).show();
				return;
			}
		     changeJsonToData1();
		     break;
		default:
			break;
		}
		 
	}
	//解析帶集合的json字串
	private void changeJsonToData1()
		{
			//用來儲存解析出來的資料,顯示在textview
			StringBuilder stringBuilder = new StringBuilder(); 
			StringBuilder stringBuilder2 = new StringBuilder(); 
			StringBuilder stringBuilder3 = new StringBuilder(); 
			PatientInformation patient;
			PatientTest patientTest;
			SleepDiary sleepDiary;
			List<PatientInformation> pInfoList=new ArrayList<PatientInformation>();
			List<PatientTest> pTestList = new ArrayList<PatientTest>();
			List<SleepDiary> sleepList = new ArrayList<SleepDiary>();
			try {
			
				object = new JSONObject(jsonString); 
				jsonArrayPatientInfo = object.getJSONArray("PatitentData");  //通過key,獲取JSONObject裡面的一個JSONArray陣列
				jsonArrayTestData = object.getJSONArray("testData");
				jsonArraySleepDiary = object.getJSONArray("sleepDiary");
				for (int i = 0; i < jsonArrayPatientInfo.length(); i++) {  //遍歷資料
					object = jsonArrayPatientInfo.getJSONObject(i); //從JSONArray裡面獲取一個JSONObject物件
					patient = new PatientInformation();
					patient.setPatient_name(object.getString("patient_name"));
					patient.setPatient_gender(object.getString("patient_gender"));
					patient.setPatient_age(object.getString("patient_age"));
					patient.setPatient_postion(object.getString("patient_postion"));
					patient.setPatient_scde(object.getString("patient_scde"));
					patient.setPatient_insomnia(object.getString("patient_insomnia"));
					patient.setPatient_mhistory(object.getString("patient_mhistory"));
					patient.setPatient_phone(object.getString("patient_phone"));
					patient.setCurrentdate(object.getString("current_date"));
					pInfoList.add(patient);
				}
			} catch (JSONException e) {
			e.printStackTrace();
		}
		for (int i = 0; i < pInfoList.size(); i++) {
			stringBuilder.append("患者姓名:"+pInfoList.get(i).getPatient_name()).append("   ").append("患者年齡:" + pInfoList.get(i).getPatient_age()).append("   ").append("性別:" + 
					pInfoList.get(i).getPatient_gender()).append("    ").append("職業:" + pInfoList.get(i).getPatient_postion()).append("   ").append("學歷:" + pInfoList.get(i).getPatient_scde()).append("  ")
					.append("失眠時間:" + pInfoList.get(i).getPatient_insomnia()).append("   ").append("既往病史: " + pInfoList.get(i).getPatient_mhistory()).append("   ").append("聯絡方式:" + 
					pInfoList.get(i).getPatient_phone()).append("   ").append("測試時間 :" + pInfoList.get(i).getCurrentdate());
				}
		for(int i = 0;i < jsonArrayTestData.length();i++){
			try {
				object = jsonArrayTestData.getJSONObject(i);
				patientTest = new PatientTest();
				patientTest.setPqsi(object.getString("pqsi"));
				patientTest.setSleepness(object.getString("sleepness"));
				patientTest.setHama(object.getString("hama"));
				patientTest.setHamd(object.getString("hamd"));
				patientTest.setIsi(object.getString("isi"));
				pTestList.add(patientTest);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
		for (int i = 0; i < pTestList.size(); i++) {
			stringBuilder2.append("pqsi:"+pTestList.get(i).getPqsi()).append("   ").append("sleepness:" + pTestList.get(i).getSleepness()).append("   ").append("hama" + 
					pTestList.get(i).getHama()).append("    ").append("hamd:" + pTestList.get(i).getHamd()).append("   ").append("isi:" + pTestList.get(i).getIsi());
			}
		System.out.println("111111111111111111111111111");
		for(int i = 0;i < jsonArraySleepDiary.length();i++){
			try {
				object = jsonArraySleepDiary.getJSONObject(i);
				System.out.println("22222222" + object);
				sleepDiary = new SleepDiary();
				sleepDiary.setDay01(object.getString("day01"));
				sleepDiary.setDay02(object.getString("day02"));
				sleepDiary.setDay03(object.getString("day03"));
				sleepDiary.setDay04(object.getString("day04"));
				sleepDiary.setDay05(object.getString("day05"));
				sleepDiary.setDay06(object.getString("day06"));
				sleepDiary.setDay07(object.getString("day07"));
				sleepList.add(sleepDiary);
				System.out.println("2222222222222222222222222");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
		for (int i = 0; i < sleepList.size(); i++) {
			stringBuilder3.append("day01:"+sleepList.get(i).getDay01()).append("   ").append("day02:" + sleepList.get(i).getDay02()).append("   ").append("day03" + 
					sleepList.get(i).getDay03()).append("    ").append("day04:" + sleepList.get(i).getDay04()).append("   ").append("day05:" + sleepList.get(i).getDay05())
					.append("   ").append("day06:" + sleepList.get(i).getDay06()).append("   ").append("day07:" + sleepList.get(i).getDay07());
			}
		
			textView.setText(stringBuilder.toString() + "\n" + stringBuilder2.toString() + "\n" + stringBuilder3);
		}
}

程式中先通過initDate()方法設定資料,再通過changeArrayDateToJson()函式將資料轉換成json資料格式,轉換後再通過changeJsonToData1()方法吧json資料轉換成普通的資料,然後在進行下一步的操作。