如何在Android Studio中使用JSON Parse

时间:2015-08-01 13:11:38

标签: android json

我想使用Android Studio解析JSON数据,但我不能。它说HTTP已被弃用。如何使用Android Studio解析这些数据。

不推荐使用HTTPClient,HTTPPost,HTTPResponse,HTTPEntity。所以我无法解析。

我的主要活动类;

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);
            }
        }

    }


}

3 个答案:

答案 0 :(得分:3)

不推荐并不意味着它不起作用,但您应该考虑更改它。

有很多很棒的网络库:

  1. OkHttp
  2. ION
  3. Volley
  4. Retrofit
  5. 还有更多。在https://android-arsenal.com

    上可以找到更多精彩内容

答案 1 :(得分:0)

我确定这是一个重复的问题,但没关系。

使用Volley(https://github.com/mcxiaoke/android-volley)它是一个非常强大的API,可以在一行中替换您尝试使用HttpClient的所有内容。

您可以在此处看到一个简单示例:https://developer.android.com/training/volley/simple.html

答案 2 :(得分:0)

            // take Info from web
            public class Omri extends AsyncTask<String, Void, String> {

                @Override
                protected String doInBackground(String... params) {
                    // ///////////////////////////////////////////////////////////////////
                    BufferedReader input = null;
                    HttpURLConnection connection = null;
                    StringBuilder response = new StringBuilder();
                    try {
                        // replace THE_ADDRESS_YOU_WANT with the url you want to
                        // comsume.
                        URL url = new URL(params[0]);

                        connection = (HttpURLConnection) url.openConnection();
                        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                            return null;
                        }

                        input = new BufferedReader(new InputStreamReader(
                                connection.getInputStream()));
                        String line = "";
                        while ((line = input.readLine()) != null) {
                            response.append(line + "\t");
                        }
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                        return null;
                    } catch (IOException e) {
                        e.printStackTrace();
                        return "IEO";
                    } finally {
                        if (input != null) {
                            try {
                                input.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (connection != null) {
                            connection.disconnect();
                        }
                    }
                    return response.toString();
                }

                ProgressDialog dialog;

                @Override
                protected void onPreExecute() {
                    // show a dialog

                    try {
                        progressDialog = new ProgressDialog(Serch.this);
                        progressDialog.setMessage("Searching"+", Please wait...");
                        progressDialog.show();
                    } catch (Exception e) {
                        post("לא יכול לחפש אנא נסה שנית");
                    }

                }

                @Override
                protected void onPostExecute(String result) {
                    if (result == null || result.length() == 0) {
                        // no result:
                        post("לא מוצא.... ");
                        progressDialog.dismiss();
                    } else {

                        try {
                            JSONObject responseObject = new JSONObject(result);
                            JSONArray searchArray = responseObject
                                    .getJSONArray("Search");
                            for (i = 0; i < searchArray.length(); i++) {
                                JSONObject searchObject =searchArray.getJSONObject(i);

                                String title = searchObject.getString("Title");

    Log.d("Omri make my day" , title );


                            }



                        } catch (JSONException e) {
                            progressDialog.dismiss();
                            Toast.makeText(Serch.this, "לא מוצא", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }

                }

            }



public void post(String str){
                Toast.makeText(Serch.this, str, Toast.LENGTH_SHORT)
                                    .show();
}

启动AsyncTask

new Omri().execute("http://www.omdbapi.com/?s=rocky");