Convert JSON Java Android - MOIP

0

I'm using the MOIP API to create a client and I can not extract the following return for JSON in JAVA:

{"id":"CUS-K2R4F6N2E9SL","ownId":"77888888888888","fullname":"ASDASDAS FULL","createdAt":"2018-10-09T01:55:42.000-03","birthDate":"1991-10-22","email":"[email protected]","phone":{"countryCode":"55","areaCode":"19","number":"92833408"},"taxDocument":{"type":"CPF","number":"36442797805"},"shippingAddress":{"zipCode":"01234000","street":"Avenida Faria Lima","streetNumber":"500","complement":"21","city":"Campinas","district":"Itaim","state":"SP","country":"BRA"},"_links":{"self":{"href":"https://sandbox.moip.com.br/v2/customers/CUS-K2R4F6N2E9SL"},"hostedAccount":{"redirectHref":"https://hostedaccount-sandbox.moip.com.br?token=2f549afa-2827-4711-8717-abc6212ade87&id=CUS-K2R4F6N2E9SL&mpa=MPA-A887D7315C56"}}}

But if it comes with error return, something of the tip:

{"errors":[{"code":"CUS-008","path":"customer.ownId","description":"O identificador prßprio deve ser único, j¹ existe um customer com o identificador informado"}]}

I can read normally, because the header contains the "errors" and in the return of success it does not have header, tried of all the forms and I do not succeed.

I'm using OKHTTP to send the data.

Here is the code snippet responsible for sending:

//Para envio de notification para Morador
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

Call post(String url, String json, Callback callback) {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
            .addHeader("Content-Type", "application/json")
            .addHeader("Authorization", "Basic KEY")
            .url(url)
            .post(body)
            .build();
    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;

public String criarClienteMoip() {

    final ProgressDialog dialog = new ProgressDialog(getContext());
    dialog.setMessage("Ajustando itens...");
    dialog.setCancelable(false);
    dialog.show();

    final String[] code = {null};

    try {
        JSONObject jsonObject = new JSONObject();
        JSONObject taxDocument = new JSONObject();
        JSONObject phone = new JSONObject();
        JSONObject shippingAddress = new JSONObject();

        //TaxDocument
        taxDocument.put("type", "CPF");
        taxDocument.put("number", "23545154");

        //phone
        phone.put("countryCode", "55");
        phone.put("areaCode", "19");
        phone.put("number", "021545154");

        //Address
        shippingAddress.put("city", "SaoPaulo");
        shippingAddress.put("complement", "21");
        shippingAddress.put("district", "Itaim");
        shippingAddress.put("street", "Avenida Faria Lima");
        shippingAddress.put("streetNumber", "500");
        shippingAddress.put("zipCode", "01234000");
        shippingAddress.put("state", "SP");
        shippingAddress.put("country", "BRA");


        jsonObject.put("ownId", "77888888888888");
        jsonObject.put("fullname", "ASDASDAS FULL");
        jsonObject.put("email", "[email protected]");
        jsonObject.put("birthDate", "1991-10-22");
        jsonObject.put("taxDocument", taxDocument);
        jsonObject.put("phone", phone);
        jsonObject.put("shippingAddress", shippingAddress);

        post("https://sandbox.moip.com.br/v2/customers/", jsonObject.toString(), new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //Something went wrong
                        Log.i("TAGS", "deu errado");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                        String responseStr = response.body().string();
                        Log.i("CODE", responseStr);
                        if (response.isSuccessful()) {
                            dialog.dismiss();
                            //Aqui eu não consigo ler o conteúdo de sucesso do retorno
                            try {
                                JSONObject jsonObject1 = new JSONObject(responseStr);
                                JSONArray jsonArray = jsonObject1.getJSONArray("id");
                                JSONObject retorno = jsonArray.getJSONObject(0);
                                code[0] = retorno.getString("id");
                                Log.i("CODE", responseStr);

                                //Executa na UI Trhead
                                getActivity().runOnUiThread(new Runnable() {
                                    public void run() {
                                        if (!code[0].equals("CUS-008")) {
                                            Util.toastLongo(getContext(), "Conta criada " + code[0]);
                                            return;
                                        }
                                    }
                                });

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

                        } else {

                            //Pega retorno em caso de falha
                            try {
                                JSONObject jsonObject1 = new JSONObject(responseStr);
                                JSONArray jsonArray = jsonObject1.getJSONArray("errors");
                                JSONObject retorno = jsonArray.getJSONObject(0);
                                code[0] = retorno.getString("code");
                                //Log.i("CODE", code[0]);
                                dialog.dismiss();

                                //Executa na UI Trhead
                                getActivity().runOnUiThread(new Runnable() {
                                    public void run() {
                                        if (code[0].equals("CUS-008")) {
                                            Util.toastLongo(getContext(), "Já possui conta no MOIP"); //Aqui eu consigo ler normalmente
                                            return;
                                        }
                                    }
                                });

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

                        }
                    }
                }
        );
    } catch (JSONException ex) {
        Log.d("Exception", "JSON exception", ex);
    }
    return code[0];

}
    
asked by anonymous 09.10.2018 / 06:58

1 answer

1

By doing jsonObject1.getJSONArray("id"); you are trying to extract an array of this attribute, but in fact it is of type String. With new JSONObject(responseStr); you already load the object correctly, then just extract as you already did. Example:

JSONObject jsonObject1 = new JSONObject(responseStr);
code[0] = jsonObject1.getString("id");
    
09.10.2018 / 22:51