如何解析 Android 中的 json 字符串?
此示例演示如何解析 Android 中的 JSON 字符串。
步骤 1 − 在 Android Studio 中创建新项目,转至文件 ⇒ 新建项目并填写创建新项目所需的所有详细信息。
步骤 2 − 将下列代码添加至 res/layout/activity_main.xml。
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout 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:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/text"
android:textSize = "30sp"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>在上述代码中,我们采取了一个文本视图来显示 json 元素名称。
步骤 3 − 将下列代码添加到 src/MainActivity.java
package com.example.myapplication;
import android.app.KeyguardManager;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
TextView textView;
String json = "{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " },"
+ " ]"
+ "}";
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
try {
final JSONObject obj = new JSONObject(json);
final JSONArray geodata = obj.getJSONArray("geodata");
final JSONObject person = geodata.getJSONObject(0);
textView.setText(person.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
}
}让我们尝试运行您的应用程序。我假设您已将您的实际 Android 移动设备与您的计算机连接起来。要从 Android Studio 运行该应用,请打开您的一个项目活动文件,并单击工具栏中的运行
图标。选择您的移动设备为选项,然后检查您的移动设备,它将显示您的默认屏幕-

点击 此处 下载项目代码
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Java 脚本
PHP