Android 解析JSON數(shù)據(jù)

2018-02-18 17:19 更新

下面的代碼顯示了如何解析JSON數(shù)據(jù)。

例子

\res\layout\main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">
  <TextView
    android:id="@+id/line1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
  />
  <TextView
    android:id="@+id/line2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
  />
  <TextView
    android:id="@+id/line3"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
  />
</LinearLayout>

主Activity Java代碼

package cn.w3cschool.myapplication3.app;
//o2fo.com

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import org.json.JSONObject;
import org.json.JSONException;

public class MainActivity extends Activity {
    private static final String JSON_STRING =
            "{"person":{"name":"XML","age":3,"children":["
                    + "{"name":"CSS","age":5},"
                    + "{"name":"HTML","age":7},"
                    + "{"name":"Javascript","age":9}"
                    + "] } }";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView line1 = (TextView)findViewById(R.id.line1);
        TextView line2 = (TextView)findViewById(R.id.line2);
        TextView line3 = (TextView)findViewById(R.id.line3);
        try {
            JSONObject person = (new JSONObject(JSON_STRING)).getJSONObject("person");
            String name = person.getString("name");
            line1.setText("This person"s name is " + name);
            line2.setText(name + " is " + person.getInt("age") + " years old.");
            line3.setText(name + " has " + person.getJSONArray("children").length()
                    + " children.");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
解析JSON數(shù)據(jù)



以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號