如何在Android上解析JSON对象?
此示例演示如何在Android上解析JSON对象。
步骤1 − 在Android Studio中创建一个新项目,转到文件 ⇒ 新建项目,并填写所有必需的详细信息以创建一个新项目。
步骤2 − 将以下依赖项添加到Gradle脚本 ⇒ build.gradle并进行同步
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.sample"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation "com.android.support:recyclerview-v7:23.0.1" // dependency file for RecyclerView
implementation 'com.android.support:cardview-v7:23.0.1' // dependency file for CardView
}步骤3 − 将以下依赖项添加到res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
步骤4 − 将以下依赖项添加到res/layout/rowlayout_main.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:id="@+id/cardView" android:layout_width="match_parent" android:layout_margin="5dp" android:layout_height="wrap_content"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dp"> <!--items for a single row of RecyclerView--> <TextView android:id="@+id/tvName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name" android:textColor="#000" android:textSize="20sp" /> <TextView android:id="@+id/tvEmail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="email@email.com" android:textColor="#000" android:textSize="15sp" /> <TextView android:id="@+id/tvMobile" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="e9999999999" android:textColor="#000" android:textSize="15sp" /> </LinearLayout> </android.support.v7.widget.CardView>
步骤5 − 将以下依赖项添加到src/MainActivity.java
package com.example.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
// ArrayList for person names, email Id's and mobile numbers
ArrayList<String> personNames=new ArrayList<>();
ArrayList<String> emailIds=new ArrayList<>();
ArrayList<String> mobileNumbers=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of RecyclerView
RecyclerView recyclerView=(RecyclerView) findViewById(R.id.recyclerView);
// set a LinearLayoutManager with default vertical orientation
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(linearLayoutManager);
try {
// get JSONObject from JSON file
JSONObject obj=new JSONObject(loadJSONFromAsset());
// fetch JSONArray named users
JSONArray userArray=obj.getJSONArray("users");
// implement for loop for getting users list data
for (int i = 0; i < userArray.length(); i++) {
// create a JSONObject for fetching single user data
JSONObject userDetail=userArray.getJSONObject(i);
// fetch email and name and store it in arraylist
personNames.add(userDetail.getString("name"));
emailIds.add(userDetail.getString("email"));
// create a object for getting contact data from JSONObject
JSONObject contact=userDetail.getJSONObject("contact");
// fetch mobile number and store it in arraylist
mobileNumbers.add(contact.getString("mobile"));
}
} catch (JSONException e) {
e.printStackTrace();
}
// call the constructor of CustomAdapter to send the reference and data to Adapter
CustomAdapter customAdapter=new CustomAdapter(MainActivity.this, personNames, emailIds, mobileNumbers);
recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView
}
public String loadJSONFromAsset() {
String json=null;
try {
InputStream is=getAssets().open("users_list.json");
int size=is.available();
byte[] buffer=new byte[size];
is.read(buffer);
is.close();
json=new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}步骤6 − 将以下依赖项添加到src/CustomAdapter.java
package com.example.sample;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
ArrayList<String> personNames;
ArrayList<String> emailIds;
ArrayList<String> mobileNumbers;
Context context;
public CustomAdapter(Context context, ArrayList<String> personNames, ArrayList<String> emailIds, ArrayList<String> mobileNumbers) {
this.context=context;
this.personNames=personNames;
this.emailIds=emailIds;
this.mobileNumbers=mobileNumbers;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// infalte the item Layout
View v=LayoutInflater.from(parent.getContext()).inflate(R.layout.rowlayout, parent, false);
MyViewHolder vh=new MyViewHolder(v); // pass the view to View Holder
return vh;
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
// set the data in items
holder.name.setText(personNames.get(position));
holder.email.setText(emailIds.get(position));
holder.mobileNo.setText(mobileNumbers.get(position));
// implement setOnClickListener event on item view.
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// display a toast with person name on item click
Toast.makeText(context, personNames.get(position), Toast.LENGTH_SHORT).show();
}
});
}
@Override
public int getItemCount() {
return personNames.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView name, email, mobileNo; // init the item view's
public MyViewHolder(View itemView) {
super(itemView);
// get the reference of item view's
name=(TextView) itemView.findViewById(R.id.tvName);
email=(TextView) itemView.findViewById(R.id.tvEmail);
mobileNo=(TextView) itemView.findViewById(R.id.tvMobile);
}
}
}步骤7 − 将以下代码添加到app/manifests/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.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中运行应用程序,请打开项目中的一个活动文件,然后单击运行
工具栏中的图标。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕−

点击这里下载项目代码。
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP