Pass list from String to JSON Object

0

I have a JSON list but it returns the following:

{"product":"[[\"5a10de2d8bb9d715c320acd8\",
 [\"5a08d4495d0e296cab3b5637\"]]"}

It is not a correct JSON.

I have a String list where I store the values and then pass it as a parameter to the JSON.

The ideas is that the answer is

 "product": [
                "5a08d4495d0e296cab3b5637"
            ]

The classes are as follows:

private RecyclerView recyclerListaProductos;
private RecyclerView.Adapter adapter;
private List<ProductosCarrito> listaProductos;
private List<Productos> productosLista;
JSONArray array = new JSONArray();
List<String> allProduct = new ArrayList<String>();

JSONObject jsonObject=new JSONObject();

private TextView textProductoCarrito;
private TextView textPrecioCarrito;
private ImageView btnComprarCarrito;

Configuracion configuracion = new Configuracion();

String orderId, status, total, product, user, nameProduct, imagenProducto, tiempo;


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

    textProductoCarrito = (TextView) findViewById(R.id.textNombreProductoCarrito);
    textProductoCarrito = (TextView) findViewById(R.id.textPrecioCarrito);
    btnComprarCarrito = (ImageView) findViewById(R.id.btnCarrritoAll);


    recyclerListaProductos = (RecyclerView) findViewById(R.id.recyProductosCarrito);
    recyclerListaProductos.setHasFixedSize(true);
    recyclerListaProductos.setLayoutManager(new LinearLayoutManager(this));

    listaProductos = new ArrayList<>();

    adapter = new AdapterProductosCarrito(listaProductos, getApplicationContext());
    recyclerListaProductos.setAdapter(adapter);

    loadRecyclerViewData();


}

private void loadRecyclerViewData() {

    Bundle datos = this.getIntent().getExtras();


    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Cargando carrito de compras...");
    progressDialog.show();

    StringRequest stringRequest = new StringRequest(Request.Method.GET,
            configuracion.rutacarrito()+"/"+datos.getString("user"),
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    progressDialog.dismiss();

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray array = jsonObject.getJSONArray("result");

                        for(int i=0; i<array.length(); i++){
                            JSONObject o = array.getJSONObject(i);

                            ProductosCarrito productos = new ProductosCarrito(
                                    o.optString("product"),
                                    o.optString("status"),
                                    o.optString("total"),
                                    o.optString("user")

                            );
                            listaProductos.add(productos);
                            allProduct.add(o.optString("product"));
                        }

                        adapter.notifyDataSetChanged();
                    }

                    catch (JSONException e){
                        e.printStackTrace();
                    }


                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();

                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);

}

public void comprarAllCarro(View v) throws JSONException {

    final Bundle datos = this.getIntent().getExtras();

        jsonObject.put("product", allProduct);

    Toast.makeText(getApplicationContext(), jsonObject.toString(), Toast.LENGTH_LONG).show();
    Log.e("ERROR", jsonObject.toString());

    orderId = "MQt6";
    status = "Pendiente";
    total = datos.getString("price");
    product = jsonObject.toString();
    user = "5a0bc3c98d37a15299268c13";
    tiempo = datos.getString("time");

        CarritoDeCompras.ComprarNetworkingCarrito n = new ComprarNetworkingCarrito();
        n.execute(configuracion.rutaOrder(), RegistroDeUsuario.Networking.NETWORK_STATE_REGISTER);

        Toast.makeText(getApplicationContext(), "Productos comprados exitosamente.", Toast.LENGTH_LONG).show();
    Log.e("ERROR", product);




    Intent intent = new Intent(getApplicationContext(), Inicio.class);
    startActivity(intent);



}

public class ComprarNetworkingCarrito extends AsyncTask {

    public static final int NETWORK_STATE_REGISTER = 1;

    @Override
    protected Object doInBackground(Object[] params) {

        getJson((String) params[0], (Integer) params[1]);
        return null;
    }


    void getJson(String url, int state) {
        //Do a HTTP POST, more secure than GET
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost request = new HttpPost(url);
        List<NameValuePair> postParameters = new ArrayList<NameValuePair>();

        boolean valid = false;

        switch (state) {

            case RegistroDeUsuario.Networking.NETWORK_STATE_REGISTER:
                //Building key value pairs to be accessed on web
                postParameters.add(new BasicNameValuePair("orderId", orderId));
                postParameters.add(new BasicNameValuePair("status", status));
                postParameters.add(new BasicNameValuePair("total", total));
                postParameters.add(new BasicNameValuePair("product", product));
                postParameters.add(new BasicNameValuePair("user", user));

                valid = true;


                break;
            default:
                // Toast.makeText(c, "Unknown state", Toast.LENGTH_SHORT).show();

        }

        if (valid == true) {
            //Reads everything that comes from server
            BufferedReader bufferedReader = null;
            StringBuffer stringBuffer = new StringBuffer("");
            try {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters);
                request.setEntity(entity);

                //Send off to server
                HttpResponse response = httpClient.execute(request);

                //Reads response and gets content
                bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

                String line = "";
                String LineSeparator = System.getProperty("line.separator");
                //Read back server output
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line + LineSeparator);
                }

                bufferedReader.close();
            } catch (Exception e) {
                //Toast.makeText(c, "Error during networking", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

            decodeResultIntoJson(stringBuffer.toString());

        } else {

        }
    }

    private void decodeResultIntoJson(String response) {

        if (response.contains("error")) {
            try {
                JSONObject jo = new JSONObject(response);
                String error = jo.getString("error");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        try {
            JSONObject jo = new JSONObject(response);

            String success = jo.getString("success");
            String message = jo.getString("message");
            // Toast.makeText(c, "Register successful", Toast.LENGTH_SHORT).show();


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
    
asked by Rovi 19.11.2017 в 15:59
source

0 answers