Android使用JSON进行数据解析

Android使用JSON进行数据解析

一、Json数据格式的定义

Json的全称:JavaScript Object Notation

Json建构于两种结构:对象(“名称/值”对的集合)和数组(值得有序列表)

1.Json对象是一个无序“名称/值对”的集合。如: {“name”: “jack”, “age”:100}

2.数组是值得有序结合。如:{“students”:[{“name”: “jack”, “age”:100} ,{“name”: “tom”, “age”:10}]}

下面我们通过访问一个JSON数据的网址连接来进行数据解析并在Android客户端进行显示(id、pinyin、name)



完成效果:


布局文件:main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="ID" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="NAME" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="PINYIN" />
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="?android:attr/listDivider" />

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

cell.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:id="@+id/id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/pinyin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

</LinearLayout>

HttpUtils类

public class HttpUtils {

	public static String getJsonString(String path) {
		try {
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(3000);
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			if (conn.getResponseCode() == 200) {
				return changeInputStream(conn.getInputStream());
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	private static String changeInputStream(InputStream inputStream) {
		// TODO Auto-generated method stub
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		String jsonString = "";
		int len = 0;
		byte[] data = new byte[1024];
		try {
			while ((len = inputStream.read(data)) != -1) {
				outputStream.write(data, 0, len);
			}
			jsonString = new String(outputStream.toByteArray());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonString;
	}
}

JsonTools类

public class JsonTools {

	public static List<City> getListPersons(String key, String jsonString) {
		List<City> list = new ArrayList<City>();
		try {
			JSONObject object = new JSONObject(jsonString);
			JSONArray array = object.getJSONArray(key);
			for (int i = 0; i < array.length(); i++) {
				JSONObject jsonObject = array.getJSONObject(i);
				City city = new City();
				city.setId(jsonObject.getInt("id"));
				city.setName(jsonObject.getString("name"));
				city.setPinyin(jsonObject.getString("pinyin"));
				list.add(city);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
}

实体类City

public class City {
	private String name;
	private int id;
	private String pinyin;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getPinyin() {
		return pinyin;
	}

	public void setPinyin(String pinyin) {
		this.pinyin = pinyin;
	}

	@Override
	public String toString() {
		return "City [name=" + name + ", id=" + id + ", pinyin=" + pinyin + "]";
	}

	public City(String name, int id, String pinyin) {
		super();
		this.name = name;
		this.id = id;
		this.pinyin = pinyin;
	}

	public City() {
		super();
	}

}

MainActivity

public class MainActivity extends Activity {

	private ListView listView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		listView = (ListView) findViewById(R.id.listview);

		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

		String path = "这里填写JSON数据的网址连接";
		List<City> cities = JsonTools.getListPersons("cities",
				HttpUtils.getJsonString(path));

		for (City city : cities) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("ID", city.getId());
			map.put("NAME", city.getName());
			map.put("PINYIN", city.getPinyin());

			data.add(map);
		}

		SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, data,
				R.layout.cell, new String[] { "ID", "NAME", "PINYIN" },
				new int[] { R.id.id, R.id.name, R.id.pinyin });
		listView.setAdapter(adapter);
	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值