安卓解析json
重点是开启网络权限
难点是调用函数
开启网络权限
</application> <uses-permission android:name="android.permission.INTERNET"> </uses-permission> </manifest>
读json的函数
public static String get(String urlString) { /*try{ HttpGet request = new HttpGet(urlString); String result=getHttpClient().execute(request,new BasicResponseHandler()); return result; }catch(IOException e){ throw e; }*/ String result=""; BufferedReader in=null; try { HttpClient client = new DefaultHttpClient(); HttpGet request=new HttpGet(urlString); HttpResponse response = client.execute(request); in=new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb=new StringBuffer(""); String line=""; String NL=System.getProperty("line.separator"); // String NL=""; while((line=in.readLine())!=null){ sb.append(line+NL); } in.close(); result=sb.toString(); result=JsonFilter(result); } catch (Exception e) { e.printStackTrace(); } finally{ if(in!=null){ try{ in.close(); }catch(IOException e){ e.printStackTrace(); } } } return result; } /* * 对json字符串进行过滤,防止乱码和黑框 */ public static String JsonFilter(String jsonstr){ return jsonstr.substring(jsonstr.indexOf("{")).replace("\r\n","\n"); }
调用函数
/*****************************************************主要是点击事件*********************************************/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Button button1 = (Button) findViewById(R.id.button1);//final获得句柄 获得句柄 final TextView textView = (TextView) findViewById(R.id.textView1); button1.setOnClickListener(new OnClickListener() { public void onClick(View v) { textView.setText(get("http://www.weather.com.cn/data/cityinfo/101010100.html")); } }); }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。