Text is returning null while parse with retrofit

response body returns null ( retrofit android)
how can i handle empty response body with retrofit 2
okhttp response body null
getting response null in android
retrofit ignore null
nullonemptyconverterfactory kotlin
retrofit response
null is not a valid element retrofit

I am trying to parse a simple json (mentioned below), and setting values to textViews. I am using retrofit and GSON converter. But while setting values to textviw, it is returning me null. I have already parsed values to recyclerview which is quite easy. But in the simple response i might be making some little mistake but not able to find it.

Help would be appreciated.

ItemDescriptionInterface
public interface ItemDescriptionInterface {
    @GET("getProductDetailByProductId?ProductId=3")
    Call<JsonObject> ITEM_DESCRIPTION_RESPONSE_CALL();
}
Activity

private void GetItemDescription() {

    Retrofit retrofit2 = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    ItemDescriptionInterface apiService = retrofit2.create(ItemDescriptionInterface.class);
    Call<JsonObject> jsonCall = apiService.ITEM_DESCRIPTION_RESPONSE_CALL();
    jsonCall.enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {

            String jsonString = response.body().toString();
            Gson gson = new Gson();
            ItemDescriptionModel model = gson.fromJson(jsonString, ItemDescriptionModel.class);
            price.setText(model.getResult().getActualPrice());//Here its not getting 

        }
        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            String msg = (t.getMessage() == null) ? "Login failed!" : t.getMessage();
            Log.d("descriptionofproduct", msg);
        }
    });

JSON response I am getting:

{
  "status": "Success",
  "response_code": 200,
  "result": [
    {
      "PId": "3",
      "ProductId": "3",
      "VendorId": "admin",
      "ProductName": "Golden Green",
      "ProductAlias": "golden-green-full-rim-",
      "MarketPrice": "500",
      "ActualPrice": "450",
      "PurchasePrice": "450",
      "Style": "3",
      "DefaultImage_url": "http:\/\/lensclone.tk\/test\.png"
    }
  ]
}
Model
public class ItemDescriptionModel {

@SerializedName("ActualPrice")
private String price;

@SerializedName("ProductDetails")
private String productDetails;

@SerializedName("DefaultImage_url")
private String imgurl;

@SerializedName("ProductName")
private String ProductName;

public ItemDescriptionModel(String price, String productDetails, String imgurl, String productName) {
    this.price = price;
    this.productDetails = productDetails;
    this.imgurl = imgurl;
    ProductName = productName;
}

public String getPrice() {
    return price;
}

public void setPrice(String price) {
    this.price = price;
}

public String getProductDetails() {
    return productDetails;
}

public void setProductDetails(String productDetails) {
    this.productDetails = productDetails;
}

public String getImgurl() {
    return imgurl;
}

public void setImgurl(String imgurl) {
    this.imgurl = imgurl;
}

public String getProductName() {
    return ProductName;
}

public void setProductName(String productName) {
    ProductName = productName;
}

}

I want to show only actual price.

Let me know if i am missing something.

ItemDescriptionInterface

public interface ItemDescriptionInterface {
    @GET("getProductDetailByProductId?ProductId=3")
    Call<ItemDescriptionModel> ITEM_DESCRIPTION_RESPONSE_CALL();
}

Activity

Retrofit retrofit2 = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    ItemDescriptionInterface apiService = retrofit2.create(ItemDescriptionInterface.class);

    Call<ItemDescriptionModel> jsonCall = apiService.ITEM_DESCRIPTION_RESPONSE_CALL();
    jsonCall.enqueue(new Callback<ItemDescriptionModel>() {
        @Override
        public void onResponse(Call<ItemDescriptionModel> call, Response<ItemDescriptionModel> response) {

            ItemDescriptionModel model = (ItemDescriptionModel) response.body();
            price.setText(model.getResult().get(0).getActualPrice());
        }
    }

Model

public class ItemDescriptionModel {

@SerializedName("status")
private String status;

@SerializedName("response_code")
private String response_code;

@SerializedName("result")
private List<Results> result;

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public String getResponse_code() {
    return response_code;
}

public void setResponse_code(String response_code) {
    this.response_code = response_code;
}

public List<Results> getResult() {
    return result;
}

public void setResult(List<Results> result) {
    this.result = result;
}

private class Results {

    @SerializedName("PId")
    private String PId;

    @SerializedName("ProductId")
    private String ProductId;

    @SerializedName("VendorId")
    private String VendorId;

    @SerializedName("ProductName")
    private String ProductName;

    @SerializedName("ProductAlias")
    private String ProductAlias;

    @SerializedName("MarketPrice")
    private String MarketPrice;

    @SerializedName("ActualPrice")
    private String ActualPrice;

    @SerializedName("PurchasePrice")
    private String PurchasePrice;

    @SerializedName("Style")
    private String Style;

    @SerializedName("DefaultImage_url")
    private String DefaultImage_url;

    public String getPId() {
        return PId;
    }

    public void setPId(String PId) {
        this.PId = PId;
    }

    public String getProductId() {
        return ProductId;
    }

    public void setProductId(String productId) {
        ProductId = productId;
    }

    public String getVendorId() {
        return VendorId;
    }

    public void setVendorId(String vendorId) {
        VendorId = vendorId;
    }

    public String getProductName() {
        return ProductName;
    }

    public void setProductName(String productName) {
        ProductName = productName;
    }

    public String getProductAlias() {
        return ProductAlias;
    }

    public void setProductAlias(String productAlias) {
        ProductAlias = productAlias;
    }

    public String getMarketPrice() {
        return MarketPrice;
    }

    public void setMarketPrice(String marketPrice) {
        MarketPrice = marketPrice;
    }

    public String getActualPrice() {
        return ActualPrice;
    }

    public void setActualPrice(String actualPrice) {
        ActualPrice = actualPrice;
    }

    public String getPurchasePrice() {
        return PurchasePrice;
    }

    public void setPurchasePrice(String purchasePrice) {
        PurchasePrice = purchasePrice;
    }

    public String getStyle() {
        return Style;
    }

    public void setStyle(String style) {
        Style = style;
    }

    public String getDefaultImage_url() {
        return DefaultImage_url;
    }

    public void setDefaultImage_url(String defaultImage_url) {
        DefaultImage_url = defaultImage_url;
    }
}}

android - Text is returning null while parse with retrofit, After updating to retrofit beta-3 I'm getting the Exception (Because of an empty body) java.io. contentLength() == 0) return null; return delegate.convert(body); } }; } } 05-12 11:57:35.040 12039-13092/com.sms.sendsms D/OkHttp: <-- 200 OK but still while converting response it throwing EOFException. If the response body only contains the JSON literal null then returning a Java null is the correct behavior here. You don't need to null-check the body every time, only in places where you expect this to actually happen (which should be rare, if ever).

Change this things.

public interface ItemDescriptionInterface {
    @GET("getProductDetailByProductId?ProductId=3")
    Call<ItemDescriptionModel> ITEM_DESCRIPTION_RESPONSE_CALL();
}
        Call<ItemDescriptionModel> itemDescriptionModelCall= apiService.ITEM_DESCRIPTION_RESPONSE_CALL();
    itemDescriptionModelCall.enqueue(new Callback<ItemDescriptionModel>() {
        @Override
        public void onResponse(Call<ItemDescriptionModel> call, retrofit2.Response<ItemDescriptionModel> response) {
            if (response!=null && response.isSuccessful() && response.body()!=null){
                String prince=response.body().getPrice();
            }
        }

        @Override
        public void onFailure(Call<ItemDescriptionModel> call, Throwable t) {

        }
    });

Response.body() is null when http code is 2xx · Issue #1734 , ErrorType return if (errorType != null && throwable is HttpException) { val error = parseError(retrofit, throwable, errorType.type) AdpNetworkException(error  If the Client returns a null TypedInput for its Response body or if the Converter returns null deserializing the body then you'll get a null value in the Callback. The OkClient and UrlConnectionClient would never return null for the body. ApacheClient would if its entity was null. None of the Converters that we supply would ever return null. So it's one of those.

Once you have received a valid response successfully, you are not parsing the json correctly. The model object does not contain the ActualPrice, this has to be parsed further from the obtained json.

You would need to create model classes for the response object (ItemDescriptionModel) as well as any nested objects within the response json, like result here. You can also use online tools like JsontoJava, etc. that can generate the model class required.

Once the model class is created as required,

Replace

price.setText(model.getPrice());

with

price.setText(model.getResult().getPrice());

Handle Empty Body · Issue #1554 · square/retrofit · GitHub, null : response.errorBody().bytes(); return MasterResponse.create(response. retrofit.responseBodyConverter(Error.class, new Annotation[0]); Error error  Lets say I want to get some of the details from JSON. Retrofit is really good way to do that. It takes care of all threading stuff. To implement Retrofit, first we must import dependencies. In your build.gradle(Module.app), add these lines in dependencies{}:

How to parse http error body using Retrofit - Dalvin, Retrofit 2 — Ignore Response Payload with Call<Void>. by Norman How to Send Plain Text Request Body · Customize In this case Retrofit will always take the response body and try to convert it to Java objects. Of course, this results in the body() method of your response object returning null . Overall  Android Studio Parsing Json Using Retrofit by Tan Woon How · Published August 11, 2015 · Updated March 25, 2016 Json is lightweight data-interchange format that is widely use in the mobile app when interchange data with the server.

retrofit2.Response.errorBody java code examples, Error parsing with Retrofit, RX and Kotlin. Anyway, us, front-end guys, should handle everything API returns and doesn't return. "exceptionType": null } 3. { Clone via HTTPS Clone with Git or checkout with SVN using the repository’s web address.

Retrofit 2, In retrofit if you want to parse JSON with dynamic keys (with dynamic names) to do: @GET("/my/api/call") void getStuff(@Body String myDynamicJson); or I got it to set that text to textviews In this tutorial, we show you how to use Jackson 1. type (String, Other Custom Objects). js). data is returned as a JSON string and  Android RecyclerView JSON Parsing using Retrofit February 28, 2016 Raj Amal Android Development 165 Comments In our previous tutorials we learned to implement a simple RecyclerView and loading image in RecyclerView using Picasso.

Comments
  • Which key is set to get model.getPrice()?
  • wait let me upload my model class as well
  • @buzzingsilently updated.
  • Is this the actual response or this is sample?
  • actual response....not sample
  • what code should i change in activity ?? can u please suggest me.??
  • its shoing error on price.setText(model.getResult()); .... also.. its not accesing getActualPrice. Should i share code again??
  • Please correct me if i am wrong, is Result class should public?
  • Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 52 path $.result
  • this is the log i am getting
  • i things your json format has some error. put this site in your json code it give all java class ..jsonschema2pojo.org