android 复杂的json数据解析
1、通过谷歌的Gson来进行解析:
json数据:sTotalString = {"message":"success","result":[{"surveyid":"1","surveyname":"B"}{surveyid":"2","surveyname":"C"}]};
public class SurveyVO { private String surveyId; private String surveyName; private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getSurveyId() { return surveyId; } public void setSurveyId(String surveyId) { this.surveyId = surveyId; } public String getSurveyName() { return surveyName; } public void setSurveyName(String surveyName) { this.surveyName = surveyName; } } public class SurveyListVO { private String message; private List<SurveyVO> result; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public List<SurveyVO> getResult() { return result; } public void setResult(List<SurveyVO> result) { this.result = result; } }
json格式转换成object类型:
public class fromGson() { sTotalString = {"message":"success","result":[{"surveyid":"1","surveyname":"B"}{"surveyid":"2","surveyname":"C"}]}; Gson gson = new Gson(); SurveyListVO surveyListVO = gson.fromJson(sTotalString, SurveyListVO.class); for (int i = 0; i < surveyListVO.getResult().size(); i++) { System.out.print(surveyListVO.getResult().get(i) .getSurveyId()); print: 1////2 System.out.print(surveyListVO.getResult().get(i) .getSurveyName()); print: B///C System.out.print(surveyListVO.getMessage()); } }
2、通过json-org.jar包进行解析:
json数据:sTotalString = {"message":"success","result":[{"surveyid":"1","surveyname":"B"}{surveyid":"2","surveyname":"C"}]};
public class SurveyVO { private String surveyId; private String surveyName; public String getSurveyId() { return surveyId; } public void setSurveyId(String surveyId) { this.surveyId = surveyId; } public String getSurveyName() { return surveyName; } public void setSurveyName(String surveyName) { this.surveyName = surveyName; } }
json格式转换成object类型:
public class fromJson() { sTotalString = {"message":"success","result":[{"surveyid":"1","surveyname":"B"}{"surveyid":"2","surveyname":"C"}]}; JSONObject json; try { json = new JSONObject(sTotalString); JSONArray results = json.getJSONArray("result"); for (int i = 0; i < results.length(); i++) { SurveyVO surveyVO = new SurveyVO(); JSONObject result = results.getJSONObject(i); System.out.println(result.getString("surveyId")+" "+result.getString("surveyName")); surveyVO.setSurveyId(result.getString("surveyId")); surveyVO.setSurveyName(result.getString("surveyName")); surveyVOList.add(surveyVO); } } catch (JSONException e) { e.printStackTrace(); } }