第一种数据解析方法
1.请求的字符串如图
在这之前先导入这两个包
import org.json.JSONException;
import org.json.JSONObject;
根据returnCode是否为0来判断登录有没有成功,如果输出日志,“登录成功”那就表示这个JSON数据已经解析成功了
这里的response就是需要解析的JSAON数据
第二种是接下来是包含JSONArray的数据解析
public static ArrayList<String>arraylist = new ArrayList<String>();
public static ArrayList<String>channelTagList = new ArrayList<String>();
public static JSONArray channelNameList= new JSONArray();
public static int count;
try{
JSONObject channellist = new JSONObject(response);//转换为JSONObject
channelNameList = channellist.getJSONArray("receivedChannel");//获取JSONArray
Log.i("第一条日志",channelNameList.getJSONObject(0).toString());
count=channelNameList.length();
String channelname1 = channelNameList.getJSONObject(0).getString("channelName");
Log.i("第二条日志", channelname1);
for(int i=0;i<count;i++){
//将name和tag数据存入动态数组内
arraylist.add(channelNameList.getJSONObject(i).getString("channelName").toString());
channelTagList.add(channelNameList.getJSONObject(i).getString("channelTag").toString());
}
}
/* 第一个日志输出结果为
05-26 19:02:59.475: I/receivedChannel(6253):
{"channelTag":"1430473934597","channelId":"1","channelName":"教务处"}
第二个日志输出结果为
05-26 19:02:59.475: I/channelName(6253): 教务处*/
catch (JSONException e) {
throw new RuntimeException(e);
}
第三种
规范json串的解析格式
public Object getObjectFromData(String key, Class c) {
JSONObject object = JSON.parseObject(JSON.toJSONString(data));
return JSON.parseObject(JSON.toJSONString(object.get(key)), c);
}
MarginInfo marginInfo = (MarginInfo) jsonBean.getObjectFromData("freeResource", MarginInfo.class);
获取对象内容为
listener.sendMarginShow(marginInfo.getFlowTotalNum(),marginInfo.getFlowRemainNum(),
marginInfo.getVoiceTotalNum(),marginInfo.getVoiceRemainNum(),
marginInfo.getMessageTotalNum(),marginInfo.getMessageRemainNum() );
对象里面均为set和get方法
package com.ailk.hodo.android.bean;
/**
* Created by apple on 16/6/11.
*/
public class MarginInfo {
private String flowTotalNum;
private String flowRemainNum;
private String voiceTotalNum;
private String voiceRemainNum;
private String messageTotalNum;
private String messageRemainNum;
public String getFlowTotalNum() {
return flowTotalNum;
}
public void setFlowTotalNum(String flowTotalNum) {
this.flowTotalNum = flowTotalNum;
}
public String getFlowRemainNum() {
return flowRemainNum;
}
public void setFlowRemainNum(String flowRemainNum) {
this.flowRemainNum = flowRemainNum;
}
public String getVoiceTotalNum() {
return voiceTotalNum;
}
public void setVoiceTotalNum(String voiceTotalNum) {
this.voiceTotalNum = voiceTotalNum;
}
public String getVoiceRemainNum() {
return voiceRemainNum;
}
public void setVoiceRemainNum(String voiceRemainNum) {
this.voiceRemainNum = voiceRemainNum;
}
public String getMessageTotalNum() {
return messageTotalNum;
}
public void setMessageTotalNum(String messageTotalNum) {
this.messageTotalNum = messageTotalNum;
}
public String getMessageRemainNum() {
return messageRemainNum;
}
public void setMessageRemainNum(String messageRemainNum) {
this.messageRemainNum = messageRemainNum;
}
}