引入gson
根據api返回數據,使用gsonFormat創建兩個實體類
具體流程參考 http://blog.csdn.net/xin917480852/article/details/50891092
使用Gson將數據存入bean中
主要代碼如下
Gson gson = new Gson();
JsonParser parse =new JsonParser(); //創建json解析器
JsonObject json=(JsonObject) parse.parse(response);
Log.i("datainfo", json.get("result").getAsString());
//Log.i("datainfo", json.get("data").getAsJsonArray().toString());
List<User> userlist=gson.fromJson(json.get("data").getAsJsonArray().toString(), new TypeToken<List<User>>(){}.getType());
將獲取到的數據顯示到界面
主要界面xml文件
activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
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="com.example.h.learn.GsonActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="368dp"
android:layout_height="wrap_content"
tools:layout_editor_absoluteY="8dp"
tools:layout_editor_absoluteX="8dp">
<Spinner
android:id="@+id/names_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</Spinner>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:layout_editor_absoluteY="30dp"
tools:layout_editor_absoluteX="8dp">
<ListView
android:id="@+id/record_listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
</LinearLayout>
</LinearLayout>
record_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="wrap_content"
android:id="@+id/record_listitem"
android:layout_width="match_parent"
android:paddingBottom="3dip"
android:paddingLeft="10dip">
<TextView
android:textColor="@android:color/holo_blue_light"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="@+id/ItemTitle"
android:textSize="20dip">
</TextView>
<TextView
android:textColor="@android:color/black"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="@+id/ItemText">
</TextView>
</LinearLayout>
spinner_item.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="horizontal" >
<TextView
android:textColor="@android:color/black"
android:id="@+id/userId"
android:layout_width="109dp"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:textColor="@android:color/black"
android:id="@+id/userName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
最終結果