Leer archivo JSON localmente en Android

El archivo json lo deberemos guardar en la carpeta assets del proyecto Android, app/src/assets/raw/archivo.json

y para leerlo usaremos la siguiente función loadJSONFromAsset(ruta archivo json)

    public String loadJSONFromAsset(String flName) {
        String json = null;
        try {
            InputStream is = this.getAssets().open(flName);
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
            Log.v("MainActivity", "Load json ok");
        } catch (IOException ex) {
            Log.v("MainActivity", "Error: " + ex.getMessage());
            ex.printStackTrace();
            return null;
        }
        return json;
    }

la función devolverá el contenido del json

Para procesar JSON en Android, podemos usar ese esquema, para transformalo en un array multiple con sus valores, muy fácil de modificar a nuestro gusto

      try {
            JSONObject obj = new JSONObject(loadJSONFromAsset("raw/test.json"));
            JSONArray m_jArry = obj.getJSONArray("formules");
            ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> m_li;

            for (int i = 0; i < m_jArry.length(); i++) {
                JSONObject jo_inside = m_jArry.getJSONObject(i);
                //Log.d("Details-->", jo_inside.getString("formule"));
                String formula_value = jo_inside.getString("formule");
                String url_value = jo_inside.getString("url");

                //Add your values in your `ArrayList` as below:
                m_li = new HashMap<String, String>();
                m_li.put("formule", formula_value);
                m_li.put("url", url_value);

                formList.add(m_li);

                for (HashMap<String, String> hashMap : formList) {
                    //System.out.println(hashMap.keySet());

                    for (String key : hashMap.keySet()) {
                        Log.v("MainAcitivity", key + ":" + hashMap.get(key));
                        //System.out.println(hashMap.get(key));
                    }
                }
            }
        }  catch (JSONException e) {
            e.printStackTrace();
        }
Fuente: Android Java; How can I parse a local JSON file from assets folder into a ListView

webserveis

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard.

0 comentarios: