JSON介紹
JSON(JavaScript Object Notation)是一種輕量級的數據交換格式,具有良好的可讀性與快速編寫的特性。它目前獲得了大多數編程語言的支持,可以在不同平臺間進行數據交換。相比於XML,它的數據體積要比XML小,編寫比XML方便,傳輸速度比XML快很多。同時,他與JavaScript的交互更加方便。在Java中,通常使用json-lib(詳情查看官網,在JAVA中使用JSON需要添加相關的jar文件,而android中自帶了json-lib,只需要import org.json.*即可使用)與Google的GSON對JSON進行操作。
JSON的數據格式
一個帶數組的的JSON格式數據展示:
Android使用JSON
1.創建一個Pet類用於作爲傳輸的數據源
package com.example.jsontest;
public class Pet {
int petid; //編號
String petname; //名稱
String pettype; //類型
public Pet(){};
public Pet(int petid, String petname, String pettype){
this.petid = petid;
this.petname = petname;
this.pettype = pettype;
}
public int getPetid() {
return petid;
}
public void setPetid(int petid) {
this.petid = petid;
}
public String getPetname() {
return petname;
}
public void setPetname(String petname) {
this.petname = petname;
}
public String getPettype() {
return pettype;
}
public void setPettype(String pettype) {
this.pettype = pettype;
}
@Override
public String toString(){
return this.getPetid() + ":" + this.getPetname() + ":" + this.getPettype();
}
}
2.將Pet數組內的數據生成JSON格式的數據
private String petToJson(Pet[] p) {
String jsonResult = "";
JSONObject object = new JSONObject(); // 創建一個總的對象
JSONArray jsonarray = new JSONArray(); // 創建一個JSON數組
try {
for (int i = 0; i < p.length; ++i) {
JSONObject jsonObj = new JSONObject(); // Pet對象,json格式,每一個JSONObject待變一個pet
jsonObj.put("petid", p[i].getPetid());
jsonObj.put("petname", p[i].getPetname());
jsonObj.put("pettype", p[i].getPettype());
jsonarray.put(jsonObj);
}
object.put("pet", jsonarray);
jsonResult = object.toString();
temp = jsonResult;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonResult;
}
3.將JSON格式的數據解析成Pet對象
private void jsonToPet(String json){
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("pet");
for(int i= 0; i < jsonArray.length(); ++i){
JSONObject object = jsonArray.getJSONObject(i);
Pet p = new Pet();
p.setPetid(object.getInt("petid"));
p.setPetname(object.getString("petname"));
p.setPettype(object.getString("pettype"));
Log.e("Pet", p.toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}