web-dev-qa-db-fra.com

Simple analyse JSON de l'URL sur Android et afficher dans listview

J'essaie d'analyser un résultat JSON récupéré à partir d'une URL dans mon Android app ...

J'ai essayé quelques exemples sur Internet, mais je ne peux pas le faire fonctionner. Les données JSON ressemblent à ceci:

[
    {
        "city_id": "1",
        "city_name": "Noida"
    },
    {
        "city_id": "2",
        "city_name": "Delhi"
    },
    {
        "city_id": "3",
        "city_name": "Gaziyabad"
    },
    {
        "city_id": "4",
        "city_name": "Gurgaon"
    },
    {
        "city_id": "5",
        "city_name": "Gr. Noida"
    }
]

Quel est le moyen le plus simple d'extraire l'URL et d'analyser les données JSON dans la liste?

45
pkdkk

Vous pouvez utiliser AsyncTask, vous devrez personnaliser pour répondre à vos besoins, mais quelque chose comme ce qui suit


La tâche async a trois méthodes principales:

  1. onPreExecute() - le plus couramment utilisé pour configurer et démarrer un dialogue de progression

  2. doInBackground() - Établit des connexions et reçoit des réponses du serveur (N'essayez PAS d'attribuer des valeurs de réponse aux éléments de l'interface graphique, il s'agit d'une erreur courante qui ne peut pas être effectuée dans un thread d'arrière-plan).

  3. onPostExecute() - Nous ne sommes plus dans le thread en arrière-plan. Nous pouvons donc manipuler l'interface utilisateur avec les données de réponse ou simplement affecter la réponse à des types de variable spécifiques.

Commençons par commencer la classe, initialiser un String pour conserver les résultats en dehors des méthodes mais à l'intérieur de la classe, puis exécuter la méthode onPreExecute() pour configurer un simple dialogue de progression.

class MyAsyncTask extends AsyncTask<String, String, Void> {

    private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
    InputStream inputStream = null;
    String result = ""; 

    protected void onPreExecute() {
        progressDialog.setMessage("Downloading your data...");
        progressDialog.show();
        progressDialog.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface arg0) {
                MyAsyncTask.this.cancel(true);
            }
        });
    }

Ensuite, nous devons configurer la connexion et comment nous voulons gérer la réponse:

    @Override
    protected Void doInBackground(String... params) {

        String url_select = "http://yoururlhere.com";

        ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

        try {
            // Set up HTTP post

            // HttpClient is more then less deprecated. Need to change to URLConnection
            HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url_select);
            httpPost.setEntity(new UrlEncodedFormEntity(param));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            // Read content & Log
            inputStream = httpEntity.getContent();
        } catch (UnsupportedEncodingException e1) {
            Log.e("UnsupportedEncodingException", e1.toString());
            e1.printStackTrace();
        } catch (ClientProtocolException e2) {
            Log.e("ClientProtocolException", e2.toString());
            e2.printStackTrace();
        } catch (IllegalStateException e3) {
            Log.e("IllegalStateException", e3.toString());
            e3.printStackTrace();
        } catch (IOException e4) {
            Log.e("IOException", e4.toString());
            e4.printStackTrace();
        }
        // Convert response to string using String Builder
        try {
            BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
            StringBuilder sBuilder = new StringBuilder();

            String line = null;
            while ((line = bReader.readLine()) != null) {
                sBuilder.append(line + "\n");
            }

            inputStream.close();
            result = sBuilder.toString();

        } catch (Exception e) {
            Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
        }
    } // protected Void doInBackground(String... params)

Enfin, ici, nous allons analyser le retour. Dans cet exemple, il s’agissait d’un tableau JSON, puis fermer le dialogue:

    protected void onPostExecute(Void v) {
        //parse JSON data
        try {
            JSONArray jArray = new JSONArray(result);    
            for(i=0; i < jArray.length(); i++) {

                JSONObject jObject = jArray.getJSONObject(i);

                String name = jObject.getString("name");
                String tab1_text = jObject.getString("tab1_text");
                int active = jObject.getInt("active");

            } // End Loop
            this.progressDialog.dismiss();
        } catch (JSONException e) {
            Log.e("JSONException", "Error: " + e.toString());
        } // catch (JSONException e)
    } // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>
83
jnthnjns

Je suggérerais d'utiliser la classe JSONParser. C'est très facile à utiliser.

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) throws IOException {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);

            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }           


    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (Exception ex) {
        Log.d("Networking", ex.getLocalizedMessage());
        throw new IOException("Error connecting");
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

Ensuite, dans votre application, créez une instance de cette classe. Vous voudrez peut-être passer le constructeur "GET" ou "POST" si vous le souhaitez.

public JSONParser jsonParser = new JSONParser();

try {

    // Building Parameters ( you can pass as many parameters as you want)
    List<NameValuePair> params = new ArrayList<NameValuePair>();

    params.add(new BasicNameValuePair("name", name));
    params.add(new BasicNameValuePair("age", 25));

    // Getting JSON Object
    JSONObject json = jsonParser.makeHttpRequest(YOUR_URL, "POST", params);
} catch (JSONException e) {
    e.printStackTrace();
}
7
Marcin S.
JSONObject(html).getString("name");

Comment obtenir le html String: Faire une requête HTTP avec Android

6
Emil Davtyan

Puisque HttpClient est obsolète, here est un bon exemple de la façon de le faire en utilisant URLConnection:

Créez une classe le nom de la classe comme HttpHandler.Java. En dessous, j'ai inclus le HttpHandler.Java fichier.

import Android.util.Log;

import Java.io.BufferedInputStream;
import Java.io.BufferedReader;
import Java.io.IOException;
import Java.io.InputStream;
import Java.io.InputStreamReader;
import Java.net.HttpURLConnection;
import Java.net.MalformedURLException;
import Java.net.ProtocolException;
import Java.net.URL;

public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

Maintenant, vous devez ouvrir activity.main.xml faire la liste de [~ # ~] json [~ # ~] en analysant les données. Le activity_main.xml code comme,

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
        xmlns:tools="http://schemas.Android.com/tools"
        Android:id="@+id/activity_main"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
        Android:paddingBottom="@dimen/activity_vertical_margin"
        Android:paddingLeft="@dimen/activity_horizontal_margin"
        Android:paddingRight="@dimen/activity_horizontal_margin"
        Android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="in.vetbossel.androidjsonparse.MainActivity">

        <ListView
            Android:id="@+id/list"
            Android:layout_width="fill_parent"
            Android:layout_height="wrap_content" />
    </RelativeLayout>
 Hereafter create one xml file, the name is `list_item.xml` used for list the all values from *JSON*. The code is,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:layout_width="fill_parent"
    Android:layout_height="wrap_content"
    Android:orientation="vertical"
    Android:padding="@dimen/activity_horizontal_margin">

    <TextView
        Android:id="@+id/name"
        Android:layout_width="fill_parent"
        Android:layout_height="wrap_content"
        Android:paddingBottom="2dip"
        Android:paddingTop="6dip"
        Android:textColor="#3498db"
        Android:textSize="16sp"
        Android:textStyle="bold" />

    <TextView
        Android:id="@+id/email"
        Android:layout_width="fill_parent"
        Android:layout_height="wrap_content"
        Android:paddingBottom="2dip"
        Android:textColor="#16a085"
        Android:textStyle="bold" />

    <TextView
        Android:id="@+id/mobile"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:textColor="#e74c3c"
        Android:textStyle="bold" />
</LinearLayout>

Analyse de JSON dans MainActivity

Obtenez la valeur de [~ # ~] json [~ # ~] , pour que l'appel Http recherche le [~ # ~] json [~ # ~] valeur. Il y a beaucoup de fichiers de bibliothèque qui seront là pour chercher les valeurs [~ # ~] json [~ # ~] telles que, bibliothèque de volley & bibliothèque de conversion, etc. La bibliothèque de volley et la bibliothèque de conversion couramment utilisé pour analyser la valeur [~ # ~] json [~ # ~] . Finalement, le MainActivity.Java code comme,

import Android.app.ProgressDialog;
import Android.os.AsyncTask;
import Android.os.Bundle;
import Android.support.v7.app.AppCompatActivity;
import Android.util.Log;
import Android.widget.ListAdapter;
import Android.widget.ListView;
import Android.widget.SimpleAdapter;
import Android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Java.util.ArrayList;
import Java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private String TAG = MainActivity.class.getSimpleName();

    private ProgressDialog pDialog;
    private ListView lv;

    // URL to get contacts JSON
    private static String url = "http://demos.vetbossel.in/ajson/sample";

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        contactList = new ArrayList<>();

        lv = (ListView) findViewById(R.id.list);

        new GetContacts().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray contacts = jsonObj.getJSONArray("contacts");

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String id = c.getString("id");
                        String name = c.getString("name");
                        String email = c.getString("email");
                        String address = c.getString("address");
                        String gender = c.getString("gender");

                        // Phone node is JSON Object
                        JSONObject phone = c.getJSONObject("phone");
                        String mobile = phone.getString("mobile");
                        String home = phone.getString("home");
                        String office = phone.getString("office");

                        // tmp hash map for single contact
                        HashMap<String, String> contact = new HashMap<>();

                        // adding each child node to HashMap key => value
                        contact.put("id", id);
                        contact.put("name", name);
                        contact.put("email", email);
                        contact.put("mobile", mobile);

                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, contactList,
                    R.layout.list_item, new String[]{"name", "email",
                    "mobile"}, new int[]{R.id.name,
                    R.id.email, R.id.mobile});

            lv.setAdapter(adapter);
        }

    }
}

Et n'oubliez pas d'ajouter une permission Internet à votre fichier manifeste:

<uses-permission Android:name="Android.permission.INTERNET" />
5
Alex Jolig
import Java.io.BufferedReader;
import Java.io.InputStream;
import Java.io.InputStreamReader;
import Java.net.HttpURLConnection;
import Java.net.URL;
import Java.util.HashMap;

public class GetJsonFromUrl {
    String url = null;

    public GetJsonFromUrl(String url) {
        this.url = url;
    }

    public String GetJsonData() {
        try {
            URL Url = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) Url.openConnection();
            InputStream is = connection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            line = sb.toString();
            connection.disconnect();
            is.close();
            sb.delete(0, sb.length());
            return line;
        } catch (Exception e) {
            return null;
        }
    }
} 

et cette utilisation de la classe pour les données de poste

import Android.util.Log;

import Java.io.BufferedReader;
import Java.io.BufferedWriter;
import Java.io.DataOutputStream;
import Java.io.InputStreamReader;
import Java.io.OutputStream;
import Java.io.OutputStreamWriter;
import Java.io.UnsupportedEncodingException;
import Java.net.HttpURLConnection;
import Java.net.URL;
import Java.net.URLEncoder;
import Java.util.HashMap;
import Java.util.Map;

import javax.net.ssl.HttpsURLConnection;

/**
 * Created by user on 11/2/16.
 */
public class sendDataToServer {
   public String postdata(String requestURL,HashMap<String,String> postDataParams){
        try {
            String response = "";
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            String line;
            BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line=br.readLine()) != null) {
                response+=line;
            }
            Log.d("test", response);
            return response;
        }catch (Exception e){
            return e.toString();
        }
    }

    public String postjson(String url,String json){
        try {

            URL obj = new URL(url);
            HttpURLConnection con= (HttpURLConnection) obj.openConnection();

            //add reuqest header
            con.setRequestMethod("POST");
            con.setRequestProperty("Accept", "application/json");
            String urlParameters = ""+json;

            // Send post request
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestProperty("Content-Type", "application/json");
            OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
            wr.write(urlParameters);
            wr.flush();
            wr.close();

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + urlParameters);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            //print result
            System.out.println(response.toString());
            return response.toString();
        }catch(Exception e){

            return e.toString();
        }
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }
        return result.toString();
    }

   /* public String postdata(String url) {
    }*/
}
3
Chandan Yadav

essayez comme:

 // your get json request to server.. 
 HttpResponse response = httpClient.execute(httpPost);
 HttpEntity entity = response.getEntity();

 if(entity != null){
    JSONObject respObject = new JSONObject(EntityUtils.toString(entity));
    String active = respObject.getString("active");   
    String name = respObject.getString("name");  
    String tab1_text = respObject.getString("tab1_text");  
    //.... 
  }
else{
       //Do something here...
    }

voir cet exemple pour obtenir et analyser la réponse json du serveur:

http://adblogcat.com/parse-json-data-from-a-web-server-and-display-on-listview/

2
ρяσѕρєя K
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response
        .getEntity().getContent()));
String line = "";

while ((line = in.readLine()) != null) {

    JSONObject jObject = new JSONObject(line);

    if (jObject.has("name")) {

        String temp = jObject.getString("name");
        Log.e("name",temp);

    }

}
1
Abdul Wahab