android,json解析

本文展示了如何从服务器获取新闻数据,并通过解析JSON响应来填充ListView。重点介绍了如何使用NewService类从指定URL获取JSON数据,解析数据结构为HashMap,并将其适配到SimpleAdapter中以显示在界面上。

MainActivity的内容:

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ListView listView = (ListView) this.findViewById(R.id.listView1);
		try {
			System.out.println("获取列表前");
			//List<Shipin> list = NewService.getLastNews();
			List<Shipin> list = NewService.getJSONList();
			System.out.println("获取列表后");
			List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
			int i=0;
			System.out.println("i:"+i);
			for (Shipin shipin : list) {
				i++;
				System.out.println("i:"+i);
				HashMap<String, Object> item = new HashMap<String, Object>();
				item.put("id", shipin.getId());
				item.put("title", shipin.getTitle());
				item.put("timelength", shipin.getTimelength());
				data.add(item);

			}
			SimpleAdapter adapter = new SimpleAdapter(this, data,
					R.layout.text, new String[] { "title", "timelength" },
					new int[] { R.id.textView1, R.id.textView2 });
			listView.setAdapter(adapter);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	

}


NewService.java


package com.example.service;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.example.model.Shipin;

public class NewService {
	private static final String tag = "NewService";

	public static List<Shipin> getJSONList() throws Exception {
		String path = "http://10.20.70.85:8080/JsonDemo/json";// 服务器地址
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		System.out.println("GEThou");
		Log.i(tag, "fsd");
		if (conn.getResponseCode() == 200) {// 若有响应
			InputStream inStream = conn.getInputStream();
			return parseJSON(inStream);
		}
		return null;
	}

	private static List<Shipin> parseJSON(InputStream inStream)
			throws Exception {//在方法里抛出异常,不然方法里的内容会有很多异常

		List<Shipin> lists = new ArrayList<Shipin>();
		// --------------以下把InputStream数据变为String---------------------
		InputStreamReader inputStreamReader = new InputStreamReader(inStream,
				Charset.forName("UTF-8"));
		StringWriter stringWriter = new StringWriter();
		char[] buffer = new char[8192];
		int count;

		while ((count = inputStreamReader.read(buffer, 0, buffer.length)) != -1) {
			stringWriter.write(buffer, 0, count);
		}
		String json = stringWriter.toString();
		// --------------以上把InputStream数据变为String---------------------

		JSONArray array = new JSONArray(json);//Json数组
		for (int i = 0; i < array.length(); i++) {

			JSONObject jsonObject = array.getJSONObject(i);//单个的Json对象
			Shipin shipin = new Shipin(jsonObject.getInt("id"),
					jsonObject.getString("title"),
					jsonObject.getInt("timelength"));
			lists.add(shipin);//加入list

		}

		return lists;
	}

}


服务器端如下:

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		Shipin []shi=new Shipin[2];
		shi[0]=new Shipin(78, "阿道夫", 54656);
		shi[1]=new Shipin(43, "斯蒂芬", 43);
		StringBuffer buffer =new StringBuffer();
		buffer.append("[");
		for (Shipin i:shi){
			buffer.append("{");
			buffer.append("id:").append(i.getId()).append(",");
			buffer.append("title:\"").append(i.getTitle()).append("\",");
			buffer.append("timelength:").append(i.getTimelength());
			buffer.append("},");
		}
		buffer.deleteCharAt(buffer.length()-1);
		buffer.append("]");
		//System.out.println(buffer.toString());
		request.setAttribute("json", buffer.toString());
		request.getRequestDispatcher("jsont.jsp").forward(request, response);
	}


jsont.jsp内容


<%@ page language="java" contentType="text/plain; charset=utf-8" import="java.util.*" pageEncoding="utf-8"%>
${json}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值