最近研究了下android 发现ANDROID 中提供的JSON 在JAVA PROJECT 中调用会报异常 还以为那格式不对弄了半天
对于数据的提取 不多说 附上代码
public class LoadMenuList extends BaseProtocol {
private final static String URL = "http://192.168.80.145:8383/plat_orcl/account/menu!getUserMenusSource.action";
public boolean loadMenuListInfo(String params) {
try {
// addNameValuePair("username", usr.getUsername());
// addNameValuePair("password", usr.getPassword());
//请求服务器并获取返回结果,这里返回JSON
pack(URL);
StringBuilder sbb = parse();
JSONObject obj = null;
if(sbb != null && sbb.indexOf("[") != -1 && sbb.indexOf("]") != -1 && sbb.lastIndexOf("]") == sbb.length()-1){
obj = new JSONObject(sbb.substring(1,sbb.length()-1).replaceAll("\"children\":null", "\"children\":[]"));
}else{
obj = this.getJSON(sbb.toString());
}
StringBuilder strb = new StringBuilder();
ArrayList<JSONObject> childrenList = getChildrenJSONArrayList(obj);
getAllListMenuText(childrenList,strb);
System.out.println(strb);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 获取菜单信息的调用方法
* @param childrenList
* @param tempSb
* @throws Exception
*/
public void getAllListMenuText(ArrayList<JSONObject> childrenList,StringBuilder tempSb)
throws Exception{
for (JSONObject jsonObject : childrenList) {
tempSb.append(jsonObject.get("text")+" | ");
System.out.println(jsonObject.get("text"));
ArrayList<JSONObject> childrenList2 = getChildrenJSONArrayList(jsonObject);
if(childrenList2 != null && childrenList2.size()>0){
getAllListMenuText(childrenList2,tempSb); //递过调用,遍历当前根节点
}
}
}
/**
* 作为存放根节点对象的调用方法,这里返回JSON用 children 存放子节点
* @param obj
* @return
* @throws Exception
*/
public ArrayList<JSONObject> getChildrenJSONArrayList(JSONObject obj) throws Exception{
ArrayList<JSONObject> jsonlist = new ArrayList<JSONObject>();
JSONArray nameList = obj.getJSONArray("children");
for (int i = 0; i < nameList.length(); i++) {
jsonlist.add((JSONObject)nameList.opt(i));
}
return jsonlist;
}
查看日志结果: