如何解析 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