第一种方式解析服务器端传过来的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 = new JSONObject(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();
}
}