如何解析以开头的 JSON 文件

3
我想解析下面的JSON文件,但是它以[开头,表明它是一个数组,然后继续使用{对象,我的当前解析器返回了一个JSON对象。 我的问题是:如何修改解析器来解析这个文件? 这样解析器就可以为其他以对象或数组开头的JSON文件服务了。 JSON文件:
[{"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解析器

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

尝试解析JSON文件。
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;
    }
}

做自己一个忙,用String json = EntityUtils.toString(httpResponse.getEntity()); 来替换掉你的大部分 getJSONFromUrl() 方法,详情请见 http://developer.android.com/reference/org/apache/http/util/EntityUtils.html#toString(org.apache.http.HttpEntity)。 - Philipp Reichart
使用EntityUtils,您的JSONParser类可以如下所示:http://pastebin.com/HwLE0kLr - Philipp Reichart
@PhilippReichart 谢谢您的回答,我会测试更改 :) - santiago92
1个回答

12

如何修改解析器以解析此文件?

1.json字符串转换为JSONArray而不是JSONObject

JSONArray jsonArray = new JSONArray(json);

2.getJSONFromUrl 方法的返回类型从 JSONObject 更改为 JSONArray

3.doInBackground 中以 JSONArray 的形式获取来自 getJSONFromUrl 方法的响应:

    JSONArray jsonArray = jParser.getJSONFromUrl(URL);

谢谢回答,我会测试更改并查看您的评论 :) - santiago92
@santiago92:好的,请测试一下,如果遇到任何问题请告诉我。 - ρяσѕρєя K

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接