首页 > 解决方案 > 在android中解析Json的问题

问题描述

我的服务器端程序员在他的服务器上为 wp 添加了 CoCart api 插件。我从服务器得到响应:

{
"0c6e4b403b2381e055e3afb9c9e82192": {
    "key": "0c6e4b403b2381e055e3afb9c9e82192",
    "product_id": 36187,
    "variation_id": 36188,
    "variation": {
        "attribute_pa_colour": "black-de",
        "attribute_pa_size": "m"
    },
    "quantity": 1,
    "data_hash": "8efa7dad6a9c192be37892171605600f",
    "line_tax_data": {
        "subtotal": [],
        "total": []
    },
    "line_subtotal": 1250,
    "line_subtotal_tax": 0,
    "line_total": 1250,
    "line_tax": 0,
    "data": {},
    "product_name": "Женское пальто - Black"
},
"7c9c27e24ba60230327a8d915f71ae70": {
    "key": "7c9c27e24ba60230327a8d915f71ae70",
    "product_id": 36169,
    "variation_id": 36170,
    "variation": {
        "attribute_pa_colour": "green",
        "attribute_pa_size": "m"
    },
    "quantity": 2,
    "data_hash": "673b79f69d443c0e3321faa0cf145f53",
    "line_tax_data": {
        "subtotal": [],
        "total": []
    },
    "line_subtotal": 3200,
    "line_subtotal_tax": 0,
    "line_total": 3200,
    "line_tax": 0,
    "data": {},
    "product_name": "Женское пальто - Green"
}

}

不幸的是,我不知道该怎么做。我使用 Java Android 的 JSONObject,但是如果每次都更改键,我如何获取对象。没错,就是产品的钥匙。谢谢)

标签: androidjson

解决方案


你可以试试这个,JSONObject给你一个keys()函数,它返回一个Iterator动态键(在你的 json 中),你可以将它与 hashmap 一起用于获取和存储动态数据 -

try {
        JSONObject productJson = new JSONObject(productJsonString);
        Iterator keys = productJson.keys();


        HashMap<String, List<String>> dynamicList = new HashMap<>();

        while (keys.hasNext()) {
            String currentDynamicKey = (String) keys.next();

            JSONObject currentArrayValue = productJson.getJSONObject(currentDynamicKey);
            ArrayList<CustomObjectWithFieldsInsideDynamicKey> currentArrayData = new ArrayList<>();
            for (int i = 0; i < currentArrayValue.length(); i++) {
                currentArrayData.add(currentArrayValue.getString(i));
            }

            dynamicList.put(currentDynamicKey, currentArrayData);
        }

    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
    }

希望这可以帮助!


推荐阅读