码迷,mamicode.com
首页 > Web开发 > 详细

JSON解析

时间:2016-05-07 08:43:11      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

这一篇是json解析的小案例,具体步骤如下:

第一步:写一个布局文件

<RelativeLayout 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"
    tools:context=".MainActivity" >
   <Button 
       android:id="@+id/btn"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:onClick="doClick"
       android:text="确定"
       />
</RelativeLayout>

第二步:MainActivity中的代码如下:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;


public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void doClick(View v){
new Thread(){
public void run() {
try {
Log.i("TAG","run()");
//path为网络路径(查看号码归属地)
String path="http://apis.juhe.cn/mobile/get?phone=18046509434&key=24f974afe33dd4b34b7df2b2ab9014a5";
//网络访问部分
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.connect();
InputStream is = connection.getInputStream();
//将流转换为字符串
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder sb = new StringBuilder();
while((line=br.readLine())!=null){
sb.append(line);
}
String results = sb.toString();
Log.d("TAG","results="+results);
System.out.println("results=="+results);
//json解析部分
JSONObject object = new JSONObject(results);
Log.d("TAG","object="+object.toString());
String string = object.getString("reason");
Log.d("TAG","string"+string.toString());
JSONObject object2 = object.getJSONObject("result");
Log.d("TAG","object2"+object2.toString());
String card = object2.getString("card");
Log.d("TAG","card="+card.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
}

第三步:添加权限

 <uses-permission android:name="android.permission.INTERNET"/>

第四步:运行测试,结果如下


技术分享

JSON解析

标签:

原文地址:http://blog.csdn.net/ljt2724960661/article/details/51330096

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!