簡體   English   中英

如何使用 retrofit 從 JSON 僅獲取某些字段

[英]How to get only certain fields from JSON with retrofit

我對 Retrofit 有疑問。 我正在開發一個 Android 應用程序,該應用程序需要從 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;
    }
}

然后我使用@GET 方法和相對 URL 到 API 端點創建了一個接口

public interface OpenFoodFactsAPI {

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

在我的片段中,我做了這個

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());
            }
        });

我在網站上嘗試了獲取請求並且它有效。 但是,在我的應用程序中返回一個空響應。

您可以在此處從 api 查看 JSON

如果您對這個問題有任何想法,請回答。 謝謝!

API中,您沒有得到確切的Product作為響應。 您將獲得另一個 object,即Product是一個子 object。

您需要創建一個響應,如下所示,

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
}

那么您的interface應該如下所示,因為您在這里期望ResponseObject

public interface OpenFoodFactsAPI {

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

這將解決您的問題。 如果您對此有任何問題,請更新我。

使用后

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

@SerializedName("status_verbose")
private String status_verbose;

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

只是改變

public int getKey() {return key;}

public String getKey() {
    return key;
}

否則

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

因為在 json 它像 "update_key": "ecoscore20210127" 一樣存在

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM