假設手機SD卡中存在「test.json」文件,內容如下:
{
"name":"wu, ShyiShiou",
"address":{
"street":"no.568 jung-jeng rd.",
"postcode":54243,
"city":"Tasotun"
},
"phoneNumber":[
{
"type":"office",
"number":"2563489"
},
{
"type":"fax",
"number":"2569834"
}
]
}
首先要讀取「test.json」文件內容並儲存到字串變數。由於最外層為JSONObject結構,因此必須以所得到的JSON格式字串建立JSONObject物件。
String sdcardDir = Environment.getExternalStorageDirectory().toString();
String jsonfile = sdcardDir+ "/" + "test.json";
FileInputStream fis = new
FileInputStream(jsonfile);
BufferedReader reader = new
BufferedReader(new InputStreamReader(
fis, "UTF-8"));
Writer writer = new
StringWriter();
char[]
buffer = new char[1024];
int n;
while
((n=reader.read(buffer)) != -1) writer.write(buffer, 0, n);
fis.close();
String jsonstr =
writer.toString();
JSONObject json = new
JSONObject(jsonstr);
之後就可依據「test.json」文件結構一層一層解讀JSON資料。例如:
String username = json.getString("name");
JSONObject jo_address = json.getJSONObject("address");
JSONArray ja_phone = json.getJSONArray("phoneNumber");
address的內容可再由jo_address進一步解讀,例如:
String street = jo_address.getString("street");
而phoneNumber內容則可再由ja_phone繼續解讀,例如:
String office_tel =
ja_phone.getJSONObject(0).getString("number");