Android解析JSON字符串
2014-11-11 13:48
316 查看
public class MainActivity extends Activity { private TextView tv_json; private String weatherInfo; //接收JSON字符串的地址 private String URl = "http://m.weather.com.cn/data/101010100.html"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_json = (TextView) findViewById(R.id.tv_json); new Thread() { public void run() { try { URL url = new URL(URl); // 联网 HttpURLConnection conn = (HttpURLConnection) url .openConnection();//联网代码要在子线程中执行 conn.setRequestMethod("GET"); conn.setConnectTimeout(4000); int code = conn.getResponseCode(); if (code == 200) {// 联网成功 InputStream is = conn.getInputStream(); String result = StreamTools.readFromStream(is); JSONObject json = new JSONObject(result); JSONObject weather = json.getJSONObject("weatherinfo"); weatherInfo = (String) weather.get("city"); System.out.println(weatherInfo); runOnUiThread(new Runnable() {//在UI线程中更新界面 @Override public void run() { // TODO Auto-generated method stub tv_json.setText(weatherInfo); } }); } else { } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }; }.start(); } }
把输入流转换成字符串的工具类
public class StreamTools { /** * @param is 输入流 * @return String 返回的字符串 * @throws IOException */ public static String readFromStream(InputStream is) throws IOException{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while((len = is.read(buffer))!=-1){ baos.write(buffer, 0, len); } is.close(); String result = baos.toString(); baos.close(); return result; } }
加上网络访问权限
<uses-permission android:name="android.permission.INTERNET"/>
相关文章推荐
- Android JSON字符串解析和构建
- [Android]四种方式解析字符串----JSON、SAX、DOM、XML
- 【Android进阶】Gson解析json字符串的简单应用
- 在android 中发送和解析json ,android处理json字符串
- android解析php输出的json格式字符串实例
- Android通过http方式获取JSON字符串并解析的注意事项(乱码,小黑框)
- android解析JSON字符串
- 解决android使用gson解析json字符串,并使用混淆编译方式打包apk遇到的问题
- android实现json数据的解析和把数据转换成json格式的字符串
- 在android 中发送和解析json ,android处理json字符串
- Android JSON字符串解析和构建 .
- 解决android使用gson解析json字符串,并使用混淆编译方式打包apk遇到的问题
- Android的数据处理:使用annotation实现JSON字符串解析为java对象
- Android之图文混排 (一)对JSON字符串的解析
- Android的数据处理:使用annotation实现JSON字符串解析为java对象
- android解析JSON字符串 (最强最简便方法)
- android解析json字符串
- android实现json数据的解析和把数据转换成json格式的字符串
- android json解析带object的字符串
- [Android]四种方式解析字符串----JSON、SAX、DOM、XML