JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。
对json就不做大篇幅的介绍了。有关json的内容请自己学习。
现在说一下。json在android 的应该。
单个对象:
void buildObject()
{
String staticObject = "{\"firstname\":\"Steve\",\"lastname\":\"Jobs\",\"cellphones\":\"0\"}";
try
{
JSONObject obj = new JSONObject(staticObject);
String x = obj.get("firstname").toString() + " " + obj.get("lastname").toString() + " has " + obj.getInt("cellphones") + " Android phones.";
Log.i("json",x);
}
catch (JSONException je)
{
}
}
数组对象: void buildJson(){
try {
InputStream is = getAssets().open("json.xml");
byte [] buffer = new byte[is.available()] ;
is.read(buffer);
String json = new String(buffer,"utf-8");
JSONArray roomPicNumUrlArray = new JSONArray(json);
for(int j =0; j < roomPicNumUrlArray.length(); j++){
JSONObject roomPicNumUrlObject = roomPicNumUrlArray.getJSONObject(j);
String firstName = roomPicNumUrlObject.get("firstName").toString();
String lastName = roomPicNumUrlObject.get("lastName").toString();
String email = roomPicNumUrlObject.get("email").toString();
Log.i("person","firstName:"+firstName+"\tlastName:"+lastName+"\temail:"+email);
}
} catch (Exception e) {
e.printStackTrace();
}
}
json.xml 文件保存到assets包下:
[
{"firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{"firstName": "Jason", "lastName":"Hunter", "email": "bbbb"},
{"firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
]
结果图: