我试图从JSONArray解析一个键,它是:
{
"server": [
{
"id": "1",
"name": "Steve",
"email": "[email protected]",
"phone": "1001001000"
}
]
}
因为,ID,名称,电子邮件和电话的密钥可以动态更改,我们必须在不教授键值的情况下解析结果。也就是说,系统必须解析密钥和值。所以我认为获取一个数组并使用iterator.hasNext()将解决问题。
JSONObject jsonObject = new JSONObject(stringBuilder.toString().trim());
JSONArray jsonArray = jsonObject.getJSONArray("server");
for (int current = 0; current < jsonArray.length(); current++){
JSONObject json_object = jsonArray.getJSONObject(current);
Iterator iterator = json_object.keys();
while (iterator.hasNext()){
hashMap.put(iterator.next().toString(), json_object.getString(iterator.next().toString()));
}
}
无论是将迭代器更改为jsonObject.keys()还是json_object.keys(),它都无法正常工作,但只解析键值“id”,并且无法解析名称,电子邮件,电话。
这是我获取JSON文件的方式:
$result = mysqli_query($conn, $sql);
$data = array();
if ($result){
while($row=mysqli_fetch_array($result)){
array_push($data,
array('id'=>$row[1],
'name'=>$row[2],
'email'=>$row[3],
'phone'=>$row[4]
));
}
header('Content-Type: application/json; charset=utf8');
$json = json_encode(array("server"=>$data), JSON_PRETTY_PRINT+JSON_UNESCAPED_UNICODE);
echo $json;
试试这个
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(loadJSONFromAsset());
JSONArray jsonArray = jsonObject.getJSONArray("server");
for (int current = 0; current < jsonArray.length(); current++){
JSONObject json_object = jsonArray.getJSONObject(current);
Iterator iterator = json_object.keys();
while( iterator.hasNext() ) {
String key = (String)iterator.next();
if ( json_object.get(key) instanceof String ) {
hashMap.put(key, json_object.getString(key));
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("OUTPUT", Arrays.asList(hashMap).toString());
OUTPUT