安卓筆記-如何解析伺服器返回的Json資料
阿新 • • 發佈:2019-01-11
第一種方式解析伺服器端傳過來的Json陣列
private List<CarInformation> jsonAnalytic(String result) { List<CarInformation> list=new ArrayList<>(); if (result == null){ Toast.makeText(getApplicationContext(), "您還未新增車輛資訊,請新增後再來", Toast.LENGTH_SHORT).show(); }else { try{ JSONObject jsonObject = newJSONObject(result); JSONArray children = jsonObject.getJSONArray("carInformations"); for (int j = 0; j < children.length(); j++) { jsonObject = children.getJSONObject(j); CarInformation carInformation = new CarInformation(); carInformation.setCarInformationSerial(jsonObject.getString("carInformationSerial")); carInformation.setCarInformationBrand(jsonObject.getString("carInformationBrand")); carInformation.setCarInformationMake(jsonObject.getString("carInformationMake")); carInformation.setCarInformationModel(jsonObject.getString("carInformationModel")); list.add(carInformation); Log.d("WL", carInformation.getCarInformationBrand());} } catch (JSONException e) { e.printStackTrace(); } } return null; }
第二種方式,解析伺服器傳過來的Json物件,並且對物件進行判斷取值
private void jsonAnalytic(String result) { try { JSONObject jsonObject = new JSONObject(result); String Status = jsonObject.getString("Status"); if(Status.equals("ok")){ String jsonObject2 = jsonObject.getString("user"); if (jsonObject2.equals("false")) { Toast.makeText(this, "賬號或者密碼錯誤", Toast.LENGTH_SHORT).show(); }else { jsonObject = jsonObject.getJSONObject("user"); Oneself user = new Oneself(); user.setOneselfIdCard(jsonObject.getString("oneselIdCard")); user.setOneselfIdName(jsonObject.getString("oneselIdName")); user.setOneselfPhone(jsonObject.getString("oneselfPhone")); user.setOneselfSerial(jsonObject.getString("oneselfSerial")); user.setOneselfName(jsonObject.getString("oneselfName")); //快取使用者ID SharedPreferences sp = getSharedPreferences("sp_demo", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("name",user.getOneselfSerial()); editor.commit(); Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); } }else if (Status.equals("error")){ Toast.makeText(this, "賬號或者密碼錯誤", Toast.LENGTH_SHORT).show(); } dismiss(); } catch (JSONException e) { e.printStackTrace(); } }