Android json解析:根据嵌套key值逐层获取最底层数据

需求:根据预先定义好的嵌套的key值一层层获取json最底层数据

主函数里的代码

String json1="{"code":0,"data":{"cid":"","cstatus":-1,"doc":1,"docsProtocolRead":0,"funcSwitch":"1","hasGiftPacks":false,"headIcon":"","isUpdate":false,"live":0,"loginToken":"e3ip3mfp-41q7-n5fq-n830-b57df8d7a677","nickName":"V友14743636","sid":"e3ip3mfp-41q7-n5fq-n830-b57df8d7a677","signStatus":1,"subCount":0,"tagLibs":[{"corner":0,"id":9001,"isVivaCity":0,"name":"畅读","specialIndex":1,"specialType":1,"type":1},{"corner":0,"id":143,"isVivaCity":0,"name":"我的","specialIndex":2,"specialType":1,"type":1},{"corner":2,"id":141,"isVivaCity":0,"name":"文化","specialIndex":0,"specialType":0,"type":1},{"corner":1,"id":182570,"isVivaCity":0,"name":"科技","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":144,"isVivaCity":0,"name":"畅读号","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":40000,"isVivaCity":0,"name":"视频精选","specialIndex":0,"specialType":0,"type":1},{"corner":2,"id":163,"isVivaCity":0,"name":"直播","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":31,"isVivaCity":0,"name":"精读","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":156,"isVivaCity":0,"name":"中医","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":11,"isVivaCity":0,"name":"军事","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":45,"isVivaCity":0,"name":"历史","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":152,"isVivaCity":0,"name":"国学","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":3,"isVivaCity":0,"name":"娱乐","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":140,"isVivaCity":0,"name":"财经","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":12,"isVivaCity":0,"name":"数码","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":6,"isVivaCity":0,"name":"汽车","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":158,"isVivaCity":0,"name":"收藏","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":5,"isVivaCity":0,"name":"体育","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":149,"isVivaCity":0,"name":"书法","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":159,"isVivaCity":0,"name":"绘画","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":146,"isVivaCity":0,"name":"读书","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":7,"isVivaCity":0,"name":"生活","specialIndex":0,"specialType":0,"type":1},{"corner":1,"id":167,"isVivaCity":0,"name":"美食美酒","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":4,"isVivaCity":0,"name":"时尚","specialIndex":0,"specialType":0,"type":1},{"corner":0,"id":20001,"isVivaCity":0,"name":"GQ男士网","specialIndex":3,"specialType":0,"type":10},{"corner":0,"id":21147,"isVivaCity":0,"name":"故事会","specialIndex":4,"specialType":0,"type":10},{"corner":0,"id":20007,"isVivaCity":0,"name":"ELLE中文网","specialIndex":5,"specialType":0,"type":10},{"corner":0,"id":21079,"isVivaCity":0,"name":"时尚网","specialIndex":6,"specialType":0,"type":10},{"corner":0,"id":21041,"isVivaCity":0,"name":"环球网","specialIndex":7,"specialType":0,"type":10},{"corner":0,"id":20008,"isVivaCity":0,"name":"名车志","specialIndex":8,"specialType":0,"type":10},{"corner":0,"id":21021,"isVivaCity":0,"name":"绘本家居","specialIndex":9,"specialType":0,"type":10},{"corner":0,"id":21120,"isVivaCity":0,"name":"17173游戏网","specialIndex":10,"specialType":0,"type":10},{"corner":0,"id":21312,"isVivaCity":0,"name":"手机中国","specialIndex":11,"specialType":0,"type":10},{"corner":0,"id":21326,"isVivaCity":0,"name":"穷游网","specialIndex":12,"specialType":0,"type":10},{"corner":0,"id":21136,"isVivaCity":0,"name":"微在趣闻社","specialIndex":13,"specialType":0,"type":10},{"corner":0,"id":21244,"isVivaCity":0,"name":"崔玉涛的育学园","specialIndex":14,"specialType":0,"type":10},{"corner":0,"id":21238,"isVivaCity":0,"name":"yoka时尚","specialIndex":15,"specialType":0,"type":10},{"corner":0,"id":21294,"isVivaCity":0,"name":"玩车教授","specialIndex":16,"specialType":0,"type":10},{"corner":0,"id":21058,"isVivaCity":0,"name":"时尚COSMO中文网","specialIndex":17,"specialType":0,"type":10},{"corner":0,"id":21178,"isVivaCity":0,"name":"丁道师","specialIndex":18,"specialType":0,"type":10},{"corner":0,"id":21160,"isVivaCity":0,"name":"万能的大熊","specialIndex":19,"specialType":0,"type":10},{"corner":0,"id":21024,"isVivaCity":0,"name":"色影无忌","specialIndex":20,"specialType":0,"type":10}],"tagName":"","tk":"96ipemcp-74q5-n73q-n8b1-d2728326872c","traceFlag":1,"type":1,"uid":14743636,"upgradeInfo":{"dataType":1,"isUpd":false,"msg":"此版本已经是最新版本.","picList":[],"type":0,"url":"","version":""},"verificationFlag":false,"videoTags":[{"bannerSequence":0,"corner":0,"cover":"","coverUrl":"","createdAt":0,"desc":"","id":40007,"index":0,"isMark":false,"isSubscribed":false,"isUpdated":false,"isVivaCity":0,"lastUpdate":0,"logo":"","logoBlank":"","logoDay":"","logoHotMedia":"","logoNight":"","name":"原创","recoHotMedia":0,"subCount":0,"topSequence":0,"type":4,"uid":0},{"bannerSequence":0,"corner":2,"cover":"","coverUrl":"","createdAt":0,"desc":"","id":163,"index":0,"isMark":false,"isSubscribed":false,"isUpdated":false,"isVivaCity":0,"lastUpdate":0,"logo":"","logoBlank":"","logoDay":"","logoHotMedia":"","logoNight":"","name":"直播","recoHotMedia":0,"subCount":0,"topSequence":0,"type":4,"uid":0},{"bannerSequence":0,"corner":0,"cover":"","coverUrl":"","createdAt":0,"desc":"","id":40000,"index":0,"isMark":false,"isSubscribed":false,"isUpdated":false,"isVivaCity":0,"lastUpdate":0,"logo":"","logoBlank":"","logoDay":"","logoHotMedia":"","logoNight":"","name":"视频精选","recoHotMedia":0,"subCount":0,"topSequence":0,"type":4,"uid":0},{"bannerSequence":0,"corner":0,"cover":"","coverUrl":"","createdAt":0,"desc":"","id":218692,"index":0,"isMark":false,"isSubscribed":false,"isUpdated":false,"isVivaCity":0,"lastUpdate":0,"logo":"","logoBlank":"","logoDay":"","logoHotMedia":"","logoNight":"","name":"黑科技","recoHotMedia":0,"subCount":0,"topSequence":0,"type":4,"uid":0},{"bannerSequence":0,"corner":0,"cover":"","coverUrl":"","createdAt":0,"desc":"","id":40001,"index":0,"isMark":false,"isSubscribed":false,"isUpdated":false,"isVivaCity":0,"lastUpdate":0,"logo":"","logoBlank":"","logoDay":"","logoHotMedia":"","logoNight":"","name":"搞笑视频","recoHotMedia":0,"subCount":0,"topSequence":0,"type":4,"uid":0},{"bannerSequence":0,"corner":0,"cover":"","coverUrl":"","createdAt":0,"desc":"","id":40002,"index":0,"isMark":false,"isSubscribed":false,"isUpdated":false,"isVivaCity":0,"lastUpdate":0,"logo":"","logoBlank":"","logoDay":"","logoHotMedia":"","logoNight":"","name":"有料","recoHotMedia":0,"subCount":0,"topSequence":0,"type":4,"uid":0},{"bannerSequence":0,"corner":0,"cover":"","coverUrl":"","createdAt":0,"desc":"","id":40003,"index":0,"isMark":false,"isSubscribed":false,"isUpdated":false,"isVivaCity":0,"lastUpdate":0,"logo":"","logoBlank":"","logoDay":"","logoHotMedia":"","logoNight":"","name":"艺道","recoHotMedia":0,"subCount":0,"topSequence":0,"type":4,"uid":0},{"bannerSequence":0,"corner":0,"cover":"","coverUrl":"","createdAt":0,"desc":"","id":40006,"index":0,"isMark":false,"isSubscribed":false,"isUpdated":false,"isVivaCity":0,"lastUpdate":0,"logo":"","logoBlank":"","logoDay":"","logoHotMedia":"","logoNight":"","name":"开讲","recoHotMedia":0,"subCount":0,"topSequence":0,"type":4,"uid":0}],"vivaCityFlag":0},"message":""}";//数据虽然长但还是贴上来了,方便实战。可以贴到json在线解析里查看一下
String rule1="data,tagLibs[]";//待提取的key值
 try {
       String temp = dealWithRule(json3,rule1);
        Log.i(TAG, "获取到的数据:"+temp);
        } catch (JSONException e) {
             e.printStackTrace();
         }

调用的两个方法

    /**
     * 根据参数rule的规则提取json数据
     * @param jsonString 待解析的json数据
     * @param rule jsonString的逐层key值,如,rule1="data,tagLibs[]";表示获取jsonString下data里tagLibs数组的某一个。[]标识获取JSONArray,否则获取JSONObject
     * @return 返回JSONObject的toString格式
     * @throws JSONException
     */
    private String dealWithRule(String jsonString, String rule) throws JSONException {
        String[] rules = rule.split(",");
        for (String key :
                rules) {
            if (!key.contains("[]")){
                jsonString = parseJson(jsonString,0,key);//递归
            }else {
                jsonString = parseJson(jsonString,1,key.substring(0,(key.length()-2)));
            }
        }
        return jsonString;
    }

    /**
     * 根据key值获取数据
     * @param jsonStr
     * @param type 0标识获取JSONObject,1标识获取JSONArray
     * @param key JSONObject的key值
     * @return   无论是JSONObject还是JSONArray,都在最后toString,因为还不知道泛型怎么用
     * @throws JSONException
     */
    public String parseJson(String jsonStr,int type,String key) throws JSONException {
        JSONObject jsonObject = new JSONObject(jsonStr);
        if (type==0){
            JSONObject jsonObject1= (JSONObject) jsonObject.get(key);
            return jsonObject1.toString();
        }else {
            JSONArray jsonObject1=  jsonObject.getJSONArray(key);
            int length = jsonObject1.length();
            Random rand = new Random();
            int random = rand.nextInt(length);
            MyLog.i(TAG,"random="+random);
            JSONObject jsonObject2 = (JSONObject) jsonObject1.get(random);
            return jsonObject2.toString();
        }
    }

改后的代码

两个方法:

private JSONObject dealWithRule1(JSONObject jsonObject, String rule) throws JSONException {
        String[] rules = rule.split(",");
        for (String key :
                rules) {
            if (!key.contains("[]")){
                jsonObject = parseJson1(jsonObject,0,key);//递归
            }else {
                jsonObject = parseJson1(jsonObject,1,key.substring(0,(key.length()-2)));
            }
        }
        return jsonObject;
    }

    public JSONObject parseJson1(JSONObject jsonStr,int type,String key) throws JSONException {
        if (type==0){
            JSONObject jsonObject1= (JSONObject) jsonStr.get(key);
            return jsonObject1;
        }else {
            JSONArray jsonObject1=  jsonStr.getJSONArray(key);
            int length = jsonObject1.length();
            Random rand = new Random();
            int random = rand.nextInt(length);
            MyLog.i(TAG,"random="+random);
            JSONObject jsonObject2 = (JSONObject) jsonObject1.get(random);
            return jsonObject2;
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,684评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,143评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,214评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,788评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,796评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,665评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,027评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,679评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,346评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,664评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,766评论 1 331
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,412评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,015评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,974评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,073评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,501评论 2 343

推荐阅读更多精彩内容