Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在androidstudio中解析JSON_Android_Json - Fatal编程技术网

如何在androidstudio中解析JSON

如何在androidstudio中解析JSON,android,json,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 and

我想使用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);
            }
        }

    }


}
导入android.content.Entity;
导入android.os.AsyncTask;
导入android.support.v7.app.AppActivity;
导入android.os.Bundle;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.widget.ListView;
导入android.widget.TextView;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.util.EntityUtils;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入java.io.IOException;
导入java.util.ArrayList;
公共类MainActivity扩展了AppCompatActivity{
列表视图列表;
国家适配器;
ArrayList国家列表;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list=(ListView)findViewById(R.id.list);
countryList=新的ArrayList();
新建CountryAsynTask()。执行(“https://restcountries.eu/rest/v1/all");
}
公共类CountryAsynTask扩展异步任务{
@凌驾
受保护的布尔doInBackground(字符串…参数){
试一试{
HttpClient=new DefaultHttpClient();
HttpPost=新的HttpPost(参数[0]);
HttpResponse response=client.execute(post);
int status=response.getStatusLine().getStatusCode();
如果(状态==200){
HttpEntity=response.getEntity();
字符串数据=EntityUtils.toString(实体);
试一试{
JSONArray JSONArray=新的JSONArray(数据);

对于(inti=0;i,我确信这是一个重复的问题,但无需担心

使用Volley()这是一个非常强大的API,它可以在一行代码中替换您使用HttpClient尝试的所有内容


这里你可以看到一个简单的例子:

不表示它不起作用,但是你应该考虑改变它。

有很多很棒的网络图书馆:


  • 还有更多。可以在

    borders
    上找到更棒的东西,这是一个json数组。
    country.setOrders(jRealObject.getString(“borders”);
                // 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();
    }
    
    new Omri().execute("http://www.omdbapi.com/?s=rocky");