how to parse a json file when starts with

android, java, json, parsing, service

Solution

I want to parse the following JSON file but is starting with [ indicating to me that is an array

When json string starting with `[` means string is `JSONArray`

how to modify the parser to parse this file?

1. Convert `json` String to `JSONArray` instead of `JSONObject`:

JSONArray jsonArray = new JSONArray(json);

2. Change return type of `getJSONFromUrl` method to `JSONArray` from `JSONObject`

3. In `doInBackground` get response from `getJSONFromUrl` method in JSONArray:

    JSONArray jsonArray = jParser.getJSONFromUrl(URL);

Problem

I want to parse the following JSON file but is starting with `[` indicating to me that is an array, and then continues with `{` objects, my current parser is returning a JSON object. My question is: how to modify the parser to parse this file? So that the parser will serve me for other JSON files, starting with objects or arrangements. JSON FILE: ``` [{"codigo":1,"contenido":[{"codigo":1,"descripcion":"Lomo completo"},{"codigo":2,"descripcion":"Cerveza 1 Lt."}],"descripcion":"1 lomo completo y 1 cerveza de lt","precio":100.0},{"codigo":2,"contenido":[{"codigo":1,"descripcion":"Lomo completo"},{"codigo":2,"descripcion":"Cerveza 1 Lt."}],"descripcion":"2 lomo completo y 2 cerveza de lt","precio":190.0},{"codigo":3,"contenido":[{"codigo":1,"descripcion":"Lomo completo"},{"codigo":2,"descripcion":"Cerveza 1 Lt."}],"descripcion":"3 lomo completo y 3 cerveza de lt","precio":280.0},{"codigo":4,"contenido":[{"codigo":1,"descripcion":"Lomo completo"},{"codigo":2,"descripcion":"Cerveza 1 Lt."}],"descripcion":"4 lomo completo y 4 cerveza de lt","precio":370.0}] ``` JSON PARSER ``` public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() {} public JSONObject getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } 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; } } ``` Try to parser JSON FILE ``` public class OfertaService extends Service { private static final String URL = "http://192.168.0.13:8080/ofertas/listado"; private static final String TAG_CODIGO = "codigo"; private static final String TAG_CONTENIDO = "contenido"; private static final String TAG_DESCRIPCION = "descripcion"; private static final String TAG_PRECIO = "precio"; private static final String TAG_CODIGO_PRODUCTO = "codigo"; private static final String TAG_DESCRIPCION_PRODUCTO = "descripcion"; @SuppressWarnings("rawtypes") private List listaOfertas = new ArrayList(); public List getListaOfertas() { return listaOfertas; } public void setListaOfertas(List listaOfertas) { this.listaOfertas = listaOfertas; } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @SuppressWarnings("unchecked") @Override public int onStartCommand(Intent intent, int flags, int startId) { try { new DoInBack().execute(); } catch (Exception e) { System.out.println("error en proceso de segundo plano DoInBack"); } return 0; } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } private class DoInBack extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... params) { JSONParser jParser = new JSONParser(); JSONArray ofertasArray = null; JSONArray productos = null; JSONObject json = jParser.getJSONFromUrl(URL); try { String codigo = json.getString(TAG_CODIGO); for (int i = 0; i < ofertasArray.length(); i++) { JSONObject of; of = ofertasArray.getJSONObject(i); String id = of.getString(TAG_CODIGO); // productos = json.getJSONArray(0); List listaProductos = new ArrayList(); for (int j = 0; j < productos.length(); j++) { JSONObject pro = productos.getJSONObject(j); String idProducto = pro.getString(TAG_CODIGO_PRODUCTO); String descProducto = pro .getString(TAG_DESCRIPCION_PRODUCTO); Hashtable<String, String> producto = new Hashtable<String, String>(); producto.put(TAG_CODIGO_PRODUCTO, idProducto); producto.put(TAG_DESCRIPCION_PRODUCTO, descProducto); listaProductos.add(producto); } String descripcionOferta = of.getString(TAG_DESCRIPCION); String precio = of.getString("precio"); Hashtable ht = new Hashtable(); ht.put(TAG_CODIGO, id); ht.put(TAG_CONTENIDO, listaProductos); ht.put(TAG_DESCRIPCION, descripcionOferta); ht.put(TAG_PRECIO, precio); listaOfertas.add(ht); } System.out.println("parseo finalizado"); } catch (Exception e) { } return null; } } ```

Original source