Home » Java » spring boot – Get values from OkHttp Response Java-Exceptionshub

spring boot – Get values from OkHttp Response Java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am trying to get values from a OkHttp response body string but am getting the following error

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

The response body string looks like this( response.body().toString() )

        {
            "MerchantRequestID":"000000000000",
            "CheckoutRequestID":"170220202216211826",
            "ResponseCode": "0",
            "ResponseDescription":"Request accepted for processing",
            "CustomerMessage":"Request accepted for processing"
        }

I am parsing it like this

Gson g = new Gson();
SuccessResponse resp = g.fromJson(resp.body().toString(),SuccessResponse.class); 

How do i get the individual values from the response string.

How to&Answers:

You can create POJO with that fields (manually or using services like this ). Then you can create instance of your POJO this way :

String json = "{'MerchantRequestID': '000000000000','CheckoutRequestID':'170220202216211826','ResponseCode': '0','ResponseDescription':'Request accepted for processing','CustomerMessage':'Request accepted for processing'}";
    Gson g = new Gson();
    Example example = g.fromJson(json, Example.class);
    System.out.print(example.getCheckoutRequestID());