如何在 Android 应用中解析 JSONArray?
本示例演示了如何在 Android 应用中解析 JSONArray。
步骤 1 − 在 Android Studio 中创建一个新项目,转到文件 ⇒ 新建项目并填写所有必需的详细信息以创建一个新项目。
步骤 2 − 将以下代码添加到 res/layout/activity_main.xml 中。
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:textSize="24sp" android:textStyle="bold" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" /> </RelativeLayout>
步骤 3 − 将以下代码添加到 src/MainActivity.java 中
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
String strJson = "{ \"Basic info\"
:[{\"Name\":\"Mash\",\"Age\":\"27\"," +
"\"Gender\":\"Male\"},{\"Name\":\"Niyaz\",\"Age\":\"23\"," +
"\"Gender\":\"Male\"}]}";
String data = "";
try {
JSONObject jsonRootObject = new JSONObject(strJson);
JSONArray jsonArray = jsonRootObject.optJSONArray("Basic info");
int i=0;
while (i < jsonArray.length()) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int age = Integer.parseInt(jsonObject.optString("Age"));
String name = jsonObject.optString("Name");
String gender = jsonObject.optString("Gender");
data += "Node"+i+" :
Name= "+ name +"
Age= "+ age +"
Gender= "+ gender + "
";
i++;
}
textView.setText(data);
} catch (JSONException e) {e.printStackTrace();}
}
}步骤 4 − 将以下代码添加到 androidManifest.xml 中
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
让我们尝试运行你的应用程序。我认为你已将真实的 Android 移动设备连接到电脑。要从 Android Studio 运行应用,打开项目的一个活动文件,然后单击工具栏中的运行
图标。选择移动设备作为选项,然后检查移动设备,其中将显示你的默认屏幕 −

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
JavaScript
PHP