import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
/** * Created by Administrator on 2016/9/15 0015. */ public class JsonObject extends Activity implements View.OnClickListener {
private String name;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(this);
}
private void sendRequestWithHttpClient(){
new Thread(new Runnable() {
@Override
public void run() {
try{
HttpClient httpClient = new DefaultHttpClient();
//指定访问的服务器地址
HttpGet httpGet = new HttpGet("http://app.api.autohome.com.cn/autov4.3/cars/seriesprice-a2-pm2-v4.3.0-b42-t1.html");
HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode()==200){
//请求和响应都成功了
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity,"utf-8");
parseJSONWithJSONObject(response);
}
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
/** * 机器是如何读取指令 * {(左花括号)指“开始读取对象” * }(右花括号)指“结束读取对象” * [(左方括号)指“开始读取数组” * ](右方括号)指“结束读取数组” * 以下根据列子 * @param jsonData */ private void parseJSONWithJSONObject(String jsonData){
try{
//第一个是花括号,所以使用JSONObject读取
JSONObject jsonArray = new JSONObject(jsonData);
//result的对应值是花括号,是对象,所以使用JSONObject读取,参数为键值
JSONObject resultObject = jsonArray.getJSONObject("result");
//fctlist的对应值是方括号,是数组,所以使用JSONArray读取,参数是键值
JSONArray fctlistArray = resultObject.getJSONArray("fctlist");
if(fctlistArray.length()==0){
return;
}
//方括号后紧跟一个左花括号,这里fctlist数组内只有1个对象,所以getJSONObject(0),数组下标
// 从0开始,获取第一个对象,所以使用JSONObject读取
JSONObject factory = fctlistArray.getJSONObject(0);
if(!factory.has("serieslist")){
return;
}
//serieslist的对应值为数组,方括号,所以使用JSONArray读取,参数为键值。
JSONArray seriesArray = factory.getJSONArray("serieslist");
//这个数组都是对象,所以使用遍历
for (int i=0;i<seriesArray.length();i++){
JSONObject series = seriesArray.getJSONObject(i);
//参数为键值
name= series.getString("name");
Log.d("1111111111",name);
}
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button:
sendRequestWithHttpClient();
break;
default:
break;
}
}
}
还没有评论,来说两句吧...