JSON解析动态key

工作中后台给我传了带动态的key的json报文的数据,由于没有弄过(key后面需要的)。

{
    "data": {
        "2016-02": [
            {
                "account_money": "10.20",
                "add_ip": "27.115.75.242",
                "add_time": "1454299507",
                "affect_money": "3.00",
                "back_money": "0.00",
                "collect_money": "0.00",
                "freeze_money": "0.00",
                "id": "330691",
                "info": "撤消提现",
                "target_uid": "0",
                "target_uname": "@网站管理员@",
                "type": "撤消提现",
                "uid": "18386"
            },
            {
                "account_money": "7.20",
                "add_ip": "27.115.75.242",
                "add_time": "1454299496",
                "affect_money": "-3.00",
                "back_money": "0.00",
                "collect_money": "0.00",
                "freeze_money": "3.00",
                "id": "330690",
                "info": "提现,默认自动扣减手续费3元",
                "target_uid": "0",
                "target_uname": "@网站管理员@",
                "type": "提现冻结",
                "uid": "18386"
            }
        ],
    },
    "success": "1"
}
```就是上面这样的,没有接触过,查资料,幸亏网上有资料,记录一下。可以通过JSONObject 的keys()方法获得一个迭代器,然后遍历所有的key,keys方法返回一个Iterator对象,它有hasNext方法,来判断是否都遍历完了,用next方法来获取下一个key





<div class="se-preview-section-delimiter">div>

这里写代码片
“`

while循环是为了得到动态key集合,for循环是为了拿到我项目中需要的数据,处理的不好。好了,谨以此文章记录我遇到的json动态key’问题。

            try {
                money_record_no_data.setVisibility(View.GONE);
                money_record_expandlv.setVisibility(View.VISIBLE);
                JSONObject obj = new JSONObject(info);
                Iterator keys = obj.keys();
                while (keys.hasNext()) {
                    moneyRecordMess = new ArrayList();
                    String key = keys.next();
                    recordDates.add(key);
                    JSONArray data = (JSONArray) obj.get(key);
                    for (int i = 0; i < data.length(); i++) {
                        MoneyRecordMess mRecordMess = new MoneyRecordMess();
                        mRecordMess.setType(data.getJSONObject(i).getString(
                                "type"));
                        mRecordMess.setAffect_money(data.getJSONObject(i)
                                .getString("affect_money"));
                        mRecordMess.setInfo(data.getJSONObject(i).getString(
                                "info"));
                        mRecordMess.setAdd_time(data.getJSONObject(i).getLong(
                                "add_time"));
                        // Log.i("type", mRecordMess.getType());
                        moneyRecordMess.add(mRecordMess);
                    }
                    mLists.add(moneyRecordMess);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

while循环是为了得到动态key集合,for循环是为了拿到我项目中需要的数据,处理的不好。好了,谨以此文章记录我遇到的json动态key’问题。

你可能感兴趣的:(学习记录)