java 解析json格式数据
下面有两种方法:
1、通过谷歌的Gson来进行解析:
json数据:sTotalString = {"message":"success","result":[{"surveyid":"1","surveyname":"B"}{surveyid":"2","surveyname":"C"}]};
两个VO类:
- 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()); print: success
- }
- }
2、通过json-org.jar包进行解析:
json数据:sTotalString = {"message":"success","result":[{"surveyid":"1","surveyname":"B"}{surveyid":"2","surveyname":"C"}]};
一个VO类:
- 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();
- }
- }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。