Android解析json数据(Gson)

来源:互联网 发布:淘宝买家好评率100% 编辑:程序博客网 时间:2024/05/20 01:12
json结构: 所有的数据(data)最终都可以分解成三种类型:
标量(scalar),也就是一个单独的字符串(string)或数字(numbers),比如"广州"这个单独的词。
序列(sequence),也就是若干个相关的数据按照一定顺序并列在一起,又叫做数组(array)或列表(List),比如"广州,上海"。
 映射(mapping),也就是一个名/值对(Name/value),即数据有一个名称,还有一个与之相对应的值,这又称作散列(hash)或字典(dictionary),比如"广东省会:广州"。
Json相关规定:
  并列的数据之间用逗号(",")分隔。
  映射用冒号(":")表示。
  映射的集合(对象)用大括号("{}")表示。
  并列数据的集合(数组)用方括号("[]")表示。 

下载 google-gson-2.2.4-release.zip

解压gson-2.2.4.jar 复制到项目根目录libs文件夹即可

先看解析后效果图,用ListView展示

 

package com.example.bottomui;import java.io.IOException;import java.io.StringReader;import java.lang.reflect.Type;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.LinkedList;import java.util.List;import java.util.Map;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.widget.ListView;import android.widget.SimpleAdapter;import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;import com.google.gson.stream.JsonReader;public class JsonDemo extends Activity {    private String jsonData = "[{\"name\":\"小明\",\"age\":28}" +            ",{\"name\":\"小红\",\"age\":23}" +            ",{\"name\":\"小李\",\"age\":23}" +            ",{\"name\":\"小林\",\"age\":23}" +            ",{\"name\":\"小狗\",\"age\":20}" +            ",{\"name\":\"小猫\",\"age\":23}" +            ",{\"name\":\"小熊\",\"age\":23}" +            ",{\"name\":\"没得小了\",\"age\":23}]";    private SimpleAdapter adapter;    ListView lv =null;    List<Map<String, Object>> jsonlist;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.jsondemo);        lv = (ListView) this.findViewById(R.id.jsonlist);        jsonlist = new ArrayList<Map<String, Object>>();//1.把JSON数据映射成一个对象,使用Gson对象的fromJson()方法获取一个对象数组        Type listType = new TypeToken<LinkedList<Customer>>() {}.getType();        Gson gson = new Gson();        LinkedList<Customer> users = gson.fromJson(jsonData, listType);        for (Iterator<Customer> iterator = users.iterator(); iterator.hasNext();) {             Customer user = (Customer) iterator.next();             Log.i("username", "name--------->" + user.getName());             Log.i("userage", "age--------->" + user.getAge());             Map<String, Object> map = new HashMap<String, Object>();                map.put("sItemTitle", user.getName());                map.put("sItemInfo", user.getAge());               // list.add(map);                jsonlist.add(map);           }        adapter = new SimpleAdapter(this, jsonlist, R.layout.jsonitem,                new String[] { "sItemTitle", "sItemInfo" }, new int[] {                R.id.sItemTitle, R.id.sItemInfo });        lv.setAdapter(adapter);               //2.通过获取JsonReader对象解析JSON数据        JsonReader reader = new JsonReader(new StringReader(jsonData));           try {               reader.beginArray();// 解析数组               while (reader.hasNext()) {                  reader.beginObject(); // 解析对象                  while (reader.hasNext()) {                      String tagName = reader.nextName(); // 键值对中的key                      if (tagName.equals("name")) { // key为name                         Log.i("username", "name--------->" + reader.nextString()); // key中的内容                      } else if (tagName.equals("age")) { // key为age                         Log.i("userage", "age--------->" + reader.nextInt()); // key中的内容                      }                  }                  reader.endObject();               }               reader.endArray();           } catch (IOException e) {               e.printStackTrace();           }    }}

在LogCat 输出查看结果:

经典的小明,小红手牵手上学的场面出现了。解析完毕!
相关两份XML文件:Jsondemo.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:background="#f5f5f5" >    <LinearLayout        android:id="@+id/json_layout"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_margin="5dip"        android:layout_marginBottom="10dip"        android:layout_marginTop="10.0dip"        android:background="@color/white"        android:gravity="center|center_horizontal|center_vertical" >        <ListView            android:id="@+id/jsonlist"            android:layout_width="fill_parent"            android:layout_height="fill_parent"            android:layout_marginLeft="10dip"            android:cacheColorHint="#00000000"            android:fadingEdge="none"            android:listSelector="#00000000"            android:paddingTop="5dip" >        </ListView>    </LinearLayout></RelativeLayout>
Jsonitem.xml

<?xml version="1.0" encoding="UTF-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="30.0dip"    android:drawingCacheQuality="high"    android:minHeight="30.0dip"    android:orientation="horizontal" >    <ImageView        android:id="@+id/sItemIcon"        android:layout_width="0dip"        android:layout_height="0dip"        android:layout_margin="1.0dip"        android:padding="2.0dip"        android:scaleType="fitXY" />    <TextView        android:id="@+id/sItemTitle"        android:layout_width="fill_parent"        android:layout_height="20.0dip"        android:layout_alignTop="@+id/sItemIcon"        android:layout_toRightOf="@+id/sItemIcon"        android:gravity="center_vertical"        android:singleLine="true"        android:text="lvshou"        android:textSize="13.0sp" />    <TextView        android:id="@+id/sItemInfo"        android:layout_width="fill_parent"        android:layout_height="0.0dip"        android:layout_below="@id/sItemTitle"        android:layout_toRightOf="@id/sItemIcon"        android:ellipsize="marquee"        android:gravity="center_vertical"        android:singleLine="true"        android:textSize="13.0sp" /></RelativeLayout>

0 0
原创粉丝点击