0

el día de hoy vengo a preguntar sobre un asunto que he estado meses desarrollando y el día de hoy me salió un error, pero no lo he podido solucionar si me pudieran ayudar me ayudaría demasiado, he estado trabajando con braintree JSON express, durante unos meses hasta el día de hoy intente hacer la prueba final, pero me salió este error donde he buscado en sitios web y ninguno lo soluciono he intentado limpiar el proyecto, rebuild the project, pero ninguno funciona.

Error: java.lang.illegalstateexception: expected begin_object but was string at line 1 column 1 path $

Este error me salió en la siguiente parte del codigo:


import com.google.gson.Gson;
        import com.google.gson.GsonBuilder;

        import retrofit2.Retrofit;
        import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
        import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {
    private static Retrofit instance;
    public static Retrofit getInstance(){

        Gson gson= new GsonBuilder()
                .setLenient()
                .create();
        if (instance==null)
            instance = new Retrofit.Builder()
                    .baseUrl("http://10.0.2.2:3000/")
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();

        return instance;
    }
}

El JSON donde se obtiene el retrofit es el siguinte:

const { Router } = require('express');
const { Transaction } = require('braintree');
const logger = require('debug');
const gateway = require('../lib/gateway');

const router = Router(); // eslint-disable-line new-cap
const debug = logger('braintree_example:router');
const TRANSACTION_SUCCESS_STATUSES = [
  Transaction.Status.Authorizing,
  Transaction.Status.Authorized,
  Transaction.Status.Settled,
  Transaction.Status.Settling,
  Transaction.Status.SettlementConfirmed,
  Transaction.Status.SettlementPending,
  Transaction.Status.SubmittedForSettlement,
];

function formatErrors(errors) {
  let formattedErrors = '';

  for (let [, { code, message }] of Object.entries(errors)) {
    formattedErrors += `Error: ${code}: ${message}
`;
  }

  return formattedErrors;
}

function createResultObject({ status }) {
  let result;

  if (TRANSACTION_SUCCESS_STATUSES.indexOf(status) !== -1) {
    result = {
      header: 'Sweet Success!',
      icon: 'success',
      message:
        'Your test transaction has been successfully processed. See the Braintree API response and try again.',
    };
  } else {
    result = {
      header: 'Transaction Failed',
      icon: 'fail',
      message: `Your test transaction has a status of ${status}. See the Braintree API response and try again.`,
    };
  }

  return result;
}

router.get('/', function(req,res){
  res.redirect('/checkouts/new');
});

router.get('/checkouts/new',function (req, res) {
  gateway.clientToken.generate({}, function (err,response){
    res.send(JSON.stringify(response));
  });

});

router.get('/checkouts/:id', (req, res) => {
  let result;
  const transactionId = req.params.id;

  gateway.transaction.find(transactionId).then((transaction) => {
    result = createResultObject(transaction);
    res.render('checkouts/show', { transaction, result });
  });
});

router.post('/checkouts', (req, res) => {
  // In production you should not take amounts directly from clients
  const { amount, payment_method_nonce: paymentMethodNonce } = req.body;

  gateway.transaction
    .sale({
      amount,
      paymentMethodNonce,
      options: { submitForSettlement: true },
    })
    .then((result) => {
      const { success, transaction } = result;

      return new Promise((resolve, reject) => {
        if (success || transaction) {
          res.redirect(`checkouts/${transaction.id}`);

          resolve();
        }

        reject(result);
      });
    })
    .catch(({ errors }) => {
      const deepErrors = errors.deepErrors();

      debug('errors from transaction.sale %O', deepErrors);

      req.flash('error', { msg: formatErrors(deepErrors) });
      res.redirect('checkouts/new');
    });
});

module.exports = router;

MainActivity:


public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_CODE= 1234;
    Button btn_pay;
    String token;
    EditText edt_amount;
    LinearLayout group_waiting, group_payments;
    CompositeDisposable compositeDisposable= new CompositeDisposable();

    IBraintreeAPI myApi;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myApi= RetrofitClient.getInstance().create(IBraintreeAPI.class);
        group_payments=(LinearLayout)findViewById(R.id.payment_group);
        group_waiting=(LinearLayout)findViewById(R.id.waiting_group);
        btn_pay=(Button)findViewById(R.id.btn_pay);
        edt_amount=(EditText)findViewById(R.id.edt_amount);
        btn_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submitPayment();
            }
        });
        compositeDisposable.add(myApi.getToken().subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Consumer<BraintreeToken>() {
            @Override
            public void accept(BraintreeToken braintreeToken) throws Exception {
                if (braintreeToken.isSuccess()){
                    token= braintreeToken.getClientToken();

                }

            }

        }));



    }

    @Override
    protected void onDestroy() {
        compositeDisposable.clear();
        super.onDestroy();
    }

    private void submitPayment() {
        DropInRequest dropInRequest= new DropInRequest().clientToken(token);
        startActivityForResult(dropInRequest.getIntent(this),REQUEST_CODE);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE){
            if (resultCode == RESULT_OK){
                DropInResult result= data.getParcelableExtra(DropInResult.EXTRA_DROP_IN_RESULT);
                PaymentMethodNonce nonce= result.getPaymentMethodNonce();
                if (!TextUtils.isEmpty(edt_amount.getText().toString())){
                    String amount= edt_amount.getText().toString();
                    compositeDisposable.add(myApi
                    .submitPayment(amount,nonce.getNonce())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<BraintreeTransaction>() {
                        @Override
                        public void accept(BraintreeTransaction braintreeTransaction) throws Exception {
                            if (braintreeTransaction.isSuccess()){
                                Toast.makeText(MainActivity.this, ""+braintreeTransaction.getTransaction().getId(), Toast.LENGTH_SHORT).show();
                            }
                            else {
                                Toast.makeText(MainActivity.this, "Payment failed!", Toast.LENGTH_SHORT).show();
                            }

                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            Toast.makeText(MainActivity.this, ""+throwable.getMessage(), Toast.LENGTH_SHORT).show();

                        }
                    }));
                }
            }
        }
    }
}

API:


public interface IBraintreeAPI {
    @GET("checkouts/new")
    Observable<BraintreeToken> getToken();

    @POST("checkouts")
    @FormUrlEncoded
    Observable<BraintreeTransaction> submitPayment(@Field("amount") String amount,
                                                   @Field("payment_method_nonce") String nonce);
}

Ante toda mano espero que me ayuden, ya que no lo he podido solucionar y ustedes son mi ultima oportunidad gracias.

3
  • 1
    El error es que la estructura del json no coincide la de tu clase java. Si quieres una mejor respuesta debes mostrar más código Commented el 14 may. 2021 a las 3:10
  • Ya hermano ya agregue nuevo código, ojala me ayudes.
    – Rob Ochoa
    Commented el 14 may. 2021 a las 13:23
  • Lo siento, no soy capaz de entender el código del backend. Pero uno de esos métodos está respondiendo con una string en vez de con un json. Para ti debería ser fácil encontrarlo. Simplemente asegurate de responder con json que tenga las mismas propiedades que tus clases de java (BraintreeToken o BraintreeTransaction) Commented el 14 may. 2021 a las 16:27

0

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

Examina otras preguntas con la etiqueta o formula tu propia pregunta.