Ana
Ana

Reputation: 21

How to get only certain fields from JSON with retrofit

I have a problem with Retrofit. I am working on an Android app which needs to get information about a product from Open Food Facts API. I tried with Retrofit, I created a class with the information I want from JSON (I only need a few fields and I didn't want to make a class with all the JSON fields, because there are over 50 I think)

public class Product {
    @SerializedName("product_name_en")
    private String name;

    @SerializedName("brands")
    private String company;

    @SerializedName("update_key")
    private int key;

    public String getName() {
        return name;
    }

    public String getCompany() {
        return company;
    }

    public int getKey() {
        return key;
    }
}

Then I created an interface with the @GET method and the relative URL to the API endpoint

public interface OpenFoodFactsAPI {

    @Headers("User-Agent: Fooducate - Android - Version 1.0")
    @GET("/api/v0/product/01223004")
    Call<Product> getProducts();
}

And inside my fragment I did this

TextView text = view.findViewById(R.id.txt);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://us.openfoodfacts.org")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        OpenFoodFactsAPI jsonPlaceHolderApi = retrofit.create(OpenFoodFactsAPI.class);
        Call<Product> call = jsonPlaceHolderApi.getProducts();
        call.enqueue(new Callback<Product>() {
            @Override
            public void onResponse(Call<Product> call, Response<Product> response) {
                if (!response.isSuccessful()) {
                    text.setText("Code: " + response.code());
                    return;
                }

                Product product = response.body();
                    String content = "";
                    content += "NAME: " + product.getName() + "\n";
                    content += "COMPANY: " + product.getCompany() + "\n";
                    content += "KEY: " + product.getKey() + "\n";
                    text.append(content);
            }
            @Override
            public void onFailure(Call<Product> call, Throwable t) {
                text.setText(t.getMessage());
            }
        });

I tried the get request on a website and it works. However, in my app an empty response is returned.

You can view the JSON from the api here

If you have any idea about this problem, please answer. Thank you!

Upvotes: 0

Views: 1524

Answers (2)

NRUSINGHA MOHARANA
NRUSINGHA MOHARANA

Reputation: 1559

After using

public class ResponseObject{
@SerializedName("status")
private int status;

@SerializedName("status_verbose")
private String status_verbose;

@SerializedName("product")
private Product product;
}

Just change

public int getKey() {return key;}

to

public String getKey() {
    return key;
}

Otherwise

Error: java.lang.NumberFormatException: For input string: "ecoscore20210127"

because in json it exists like "update_key": "ecoscore20210127"

Upvotes: 0

Sajith
Sajith

Reputation: 771

From the API you are not getting exactly the Product as response. You are getting another object which is Product is a child object.

You need to create a response Like below,

public class ResponseObject{
  @SerializedName("status")
  private int status;

  @SerializedName("status_verbose")
  private String status_verbose;

  @SerializedName("product")
  private Product product;

   //getters and setters goes here
}

then your interface should be like below as you are expecting ResponseObject here.

public interface OpenFoodFactsAPI {

@Headers("User-Agent: Fooducate - Android - Version 1.0")
@GET("/api/v0/product/01223004")
Call<ResponseObject> getProducts();
}

This will solve your problem. Update me If you have any problem with this.

Upvotes: 2

Related Questions