2.建立獨立物件類別LocaJSON.class,內含三種建構子形式,以及setter&getter方法(自己寫!)。
屬性依照自己所需編寫,下面只是舉例。
public class LocaJSON {
String username;
String userid;
String longitude;
String latitude;
String date;
String time;
String massage;
String ap_ip;
String ap_ssid;
String ap_rssi;
public LocaJSON(String username, String userid, String longitude, String latitude, String date, String time, String massage, String ap_ip, String ap_ssid, String ap_rssi) {
this.username = username;
this.userid = userid;
this.longitude = longitude;
this.latitude = latitude;
this.date = date;
this.time = time;
this.massage = massage;
this.ap_ip = ap_ip;
this.ap_ssid = ap_ssid;
this.ap_rssi = ap_rssi; }
public LocaJSON() {
}
public LocaJSON(JSONObject jsonObject) {
try {
username=jsonObject.getString("username");
userid=jsonObject.getString("userid");
longitude=jsonObject.getString("longitude");
latitude=jsonObject.getString("latitude");
date=jsonObject.getString("date");
time=jsonObject.getString("time");
massage=jsonObject.getString("m_code");
ap_ip=jsonObject.getString("ap_ip");
ap_ssid=jsonObject.getString("ap_ssid");
ap_rssi=jsonObject.getString("ap_rssi");
} catch (JSONException e) {
e.printStackTrace(); }
}
3.藉由以下程式即可將字串轉存至JSONArray
locaJSONS = new ArrayList<>();
try{
JSONArray jsonArray =new JSONArray(json);
jlength=jsonArray.length();
Log.d("資料數f ", String.valueOf(jlength));
for (int i = 0; i < jlength; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
LocaJSON locaJSON = new LocaJSON(jsonObject);
locaJSONS.add(locaJSON);
}
}catch (JSONException e){
Log.d("Fail 3",e.toString());
}
4.資料已存入locaJSONS中,可供運用。
沒有留言:
張貼留言