android - 在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,但是如果每次都更改键,我如何获取对象。没错,就是产品的钥匙。谢谢)
解决方案
你可以试试这个,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();
}
希望这可以帮助!
推荐阅读
- javascript - 如何格式化生日?
- c - readdir() 没有给我 '.' Arch Linux Manjaro 上的和 '..' 目录,但在 NixOS 上确实如此
- c++ - C ++中的堆栈自动变量
- php - 自定义表单的多选模板
- event-sourcing - eventstore 是否需要事件溯源?
- c# - 获取带有特定标签的每个 Button
- amazon-web-services - 仅通过删除 CloudFormation 堆栈来允许删除 AWS 资源
- echarts - Echarts 将数据集中的属性分配为标签
- c# - 在 Xamarin.Android 中的布局之间移动
- javascript - 在 Laravel 中选择后下拉列表重置