Convert JSON Java Android - MOIP

Asked

Viewed 92 times

0

I am using the MOIP API to create a client and cannot extract the return below 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 the return, something from 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 the return of success has no header, I tried in every way and I do not succeed.

I am using OKHTTP to send the data.

Follows code excerpt 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];

}
  • Could you add a snippet of your code? Which framework are you using to communicate? Knowing the framework, if you are using one, it is easier to create an example to elucidate you.

  • @Tássioauad updated the post with the requested data.

1 answer

1


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

JSONObject jsonObject1 = new JSONObject(responseStr);
code[0] = jsonObject1.getString("id");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.