【发布时间】:2015-10-24 01:55:35
【问题描述】:
我想使用 Android Studio 解析 JSON 数据,但我不能。它说 HTTP 已被弃用。如何使用 Android Studio 解析这些数据。
HTTPClient、HTTPPost、HTTPResponse、HTTPEntity 已弃用。所以我无法解析。
我的 MainActivity 类;
import android.content.Entity;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView list;
CountryAdapter adapter;
ArrayList<Country> countryList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView)findViewById(R.id.list);
countryList = new ArrayList<Country>();
new CountryAsynTask().execute("https://restcountries.eu/rest/v1/all");
}
public class CountryAsynTask extends AsyncTask<String, Void, Boolean>{
@Override
protected Boolean doInBackground(String... params) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
if(status == 200){
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
try{
JSONArray jsonArray = new JSONArray(data);
for (int i=0; i<jsonArray.length();i++){
Country country = new Country();
JSONObject jRealObject = jsonArray.getJSONObject(i);
country.setName(jRealObject.getString("name"));
country.setPopulation(jRealObject.getString("population"));
country.setCapital(jRealObject.getString("capital"));
country.setRegion(jRealObject.getString("region"));
country.setBorders(jRealObject.getString("borders"));
country.setLblBorders("Borders");
country.setFlag("http://www.geonames.org/flags/x/" + jRealObject.getString("name").toLowerCase().substring(0, 1) + ".gif");
countryList.add(country);
}
}catch (JSONException e){
throw new RuntimeException();
}
return true;
}
}catch (ClientProtocolException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(result == false){
//data was not parse
}else{
CountryAdapter adapter = new CountryAdapter(getApplicationContext(),R.layout.row,countryList);
list.setAdapter(adapter);
}
}
}
}
【问题讨论】:
-
borders是一个 json 数组。country.setBorders(jRealObject.getString("borders"));错了