您的位置:首页 > 移动开发 > Android开发

Android 开发工具类 25_getJSON

2015-05-29 22:34 417 查看
获取 JSON 数据并解析

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

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

import com.wangjialin.internet.json.domain.News;
import com.wangjialin.internet.json.utils.StreamTool;

public class NewsService {

/**
* 获取最新视频资讯
* @return
* @throws Exception
*/
public static List<News> getJSONLastNews() throws Exception{

String path = "http://192.168.1.103:8080/ServerForJSON/NewsListServlet";
HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");

if(conn.getResponseCode() == 200){
InputStream json = conn.getInputStream();
return parseJSON(json);
}
return null;
}

private static List<News> parseJSON(InputStream jsonStream) throws Exception{

List<News> list = new ArrayList<News>();
byte[] data = StreamTool.read(jsonStream);
String json = new String(data);
JSONArray jsonArray = new JSONArray(json);

for(int i = 0; i < jsonArray.length() ; i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = jsonObject.getInt("id");
String title = jsonObject.getString("title");
int timelength = jsonObject.getInt("timelength");
list.add(new News(id, title, timelength));
}
return list;
}
}


StreamTool

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class StreamTool {
/**
* 从流中读取数据
* @param inStream
* @return
*/
public static byte[] read(InputStream inStream) throws Exception{

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;

while((len = inStream.read(buffer)) != -1){
outputStream.write(buffer, 0, len);
}

inStream.close();
return outputStream.toByteArray();
}
}


显示

public class MainActivity extends Activity {
/** Called when the activity is first created. */
List<News> newes;
List<HashMap<String, Object>> data = null;;
String length;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);
ListView listView = (ListView) this.findViewById(R.id.listView);

length = this.getResources().getString(R.string.length);

try{
newes = NewsService.getJSONLastNews();
data = new ArrayList<HashMap<String,Object>>();
for(News news : newes){
HashMap<String, Object> item = new HashMap<String, Object>();
item.put("id", news.getId());
item.put("title", news.getTitle());
item.put("timelength", length + news.getTimelength());
data.add(item);
}

SimpleAdapter adapter = new SimpleAdapter(this,
data, R.layout.item,
new String[]{"title", "timelength"},
new int[]{R.id.title, R.id.timelength}
);
listView.setAdapter(adapter);
}catch(Exception e)
{
e.printStackTrace();
};
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: