【问题标题】:JSON (POJO) model responseJSON (POJO) 模型响应
【发布时间】:2019-08-01 13:33:41
【问题描述】:

我的 JSON 响应模型有问题。

我正在使用 hitbtc API:https://api.hitbtc.com/api/2/public/currency

当我将此文件转换为 POJO 模型时,我只有这个文件:

public class Currency {

@SerializedName("id")
@Expose
private String id;
@SerializedName("fullName")
@Expose
private String fullName;
@SerializedName("crypto")
@Expose
private Boolean crypto;
@SerializedName("payinEnabled")
@Expose
private Boolean payinEnabled;
@SerializedName("payinPaymentId")
@Expose
private Boolean payinPaymentId;
@SerializedName("payinConfirmations")
@Expose
private Integer payinConfirmations;
@SerializedName("payoutEnabled")
@Expose
private Boolean payoutEnabled;
@SerializedName("payoutIsPaymentId")
@Expose
private Boolean payoutIsPaymentId;
@SerializedName("transferEnabled")
@Expose
private Boolean transferEnabled;
@SerializedName("delisted")
@Expose
private Boolean delisted;
@SerializedName("payoutFee")
@Expose
private String payoutFee;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getFullName() {
    return fullName;
}

public void setFullName(String fullName) {
    this.fullName = fullName;
}

public Boolean getCrypto() {
    return crypto;
}

public void setCrypto(Boolean crypto) {
    this.crypto = crypto;
}

public Boolean getPayinEnabled() {
    return payinEnabled;
}

public void setPayinEnabled(Boolean payinEnabled) {
    this.payinEnabled = payinEnabled;
}

public Boolean getPayinPaymentId() {
    return payinPaymentId;
}

public void setPayinPaymentId(Boolean payinPaymentId) {
    this.payinPaymentId = payinPaymentId;
}

public Integer getPayinConfirmations() {
    return payinConfirmations;
}

public void setPayinConfirmations(Integer payinConfirmations) {
    this.payinConfirmations = payinConfirmations;
}

public Boolean getPayoutEnabled() {
    return payoutEnabled;
}

public void setPayoutEnabled(Boolean payoutEnabled) {
    this.payoutEnabled = payoutEnabled;
}

public Boolean getPayoutIsPaymentId() {
    return payoutIsPaymentId;
}

public void setPayoutIsPaymentId(Boolean payoutIsPaymentId) {
    this.payoutIsPaymentId = payoutIsPaymentId;
}

public Boolean getTransferEnabled() {
    return transferEnabled;
}

public void setTransferEnabled(Boolean transferEnabled) {
    this.transferEnabled = transferEnabled;
}

public Boolean getDelisted() {
    return delisted;
}

public void setDelisted(Boolean delisted) {
    this.delisted = delisted;
}

public String getPayoutFee() {
    return payoutFee;
}

public void setPayoutFee(String payoutFee) {
    this.payoutFee = payoutFee;
}

}

下一步我想获取项目列表,看起来像这里:

 public class CurrencyResponse {
@SerializedName("page")
private int page;
@SerializedName("results")
private List<Currency> results;
@SerializedName("total_results")
private int totalResults;
@SerializedName("total_pages")
private int totalPages;

public int getPage() {
    return page;
}

public void setPage(int page) {
    this.page = page;
}

public List<Currency> getResults() {
    return results;
}

public void setResults(List<Currency> results) {
    this.results = results;
}

public int getTotalResults() {
    return totalResults;
}

public void setTotalResults(int totalResults) {
    this.totalResults = totalResults;
}

public int getTotalPages() {
    return totalPages;
}

public void setTotalPages(int totalPages) {
    this.totalPages = totalPages;
}
}

当我尝试制作适配器并显示我的货币列表(现在我需要列表视图中唯一的货币名称)时,我收到了nullPointException

我知道我在某个地方犯了一个分类错误,但我在 RESTfull API 方面仍然缺乏经验。

如果您有任何建议可以帮助我,我将非常高兴。

编辑: CurrenciesAdapter.java:

public class CurrenciesAdapter extends 
RecyclerView.Adapter<CurrenciesAdapter.CurrencyViewHolder> {

private List<Currency> currencies;
private int rowLayout;
private Context context;


public static class CurrencyViewHolder extends RecyclerView.ViewHolder {
    LinearLayout currenciesLayout;
    TextView currencyTitle;
    TextView data;
    TextView currencyDescription;
    TextView rating;


    public CurrencyViewHolder(View v) {
        super(v);
        currenciesLayout = (LinearLayout) v.findViewById(R.id.currencies_layout);
        currencyTitle = (TextView) v.findViewById(R.id.title);
        data = (TextView) v.findViewById(R.id.subtitle);
        currencyDescription = (TextView) v.findViewById(R.id.description);
        //rating = (TextView) v.findViewById(R.id.rating);
    }
}

public CurrenciesAdapter(List<Currency> currencies, int rowLayout, Context context) {
    this.currencies = currencies;
    this.rowLayout = rowLayout;
    this.context = context;
}

@Override
public CurrenciesAdapter.CurrencyViewHolder onCreateViewHolder(ViewGroup parent,
                                                            int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
    return new CurrencyViewHolder(view);
}


@Override
public void onBindViewHolder(CurrencyViewHolder holder, final int position) {
    holder.currencyTitle.setText(currencies.get(position).getFullName());
    holder.data.setText(currencies.get(position).getPayoutFee());
    if(currencies.get(position).getPayinEnabled()== true) {
        holder.currencyDescription.setText("true");
    }
    else holder.currencyDescription.setText("false");
   // holder.rating.setText(currencies.get(position).getVoteAverage().toString());
}

@Override
public int getItemCount() {
    return currencies.size();
}
}

MainActivity.java:

   public class MainActivity extends AppCompatActivity {

   private static final String TAG = MainActivity.class.getSimpleName();


// TODO - insert your themoviedb.org API KEY here
private final static String API_KEY = "My_key";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (API_KEY.isEmpty()) {
        Toast.makeText(getApplicationContext(), "Please obtain your API KEY from hitbtc.com first!", Toast.LENGTH_LONG).show();
        return;
    }

    final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.movies_recycler_view);
    LinearLayoutManager manager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(manager);
    recyclerView.setHasFixedSize(true);



    ApiInterface apiService =
            ApiClient.getClient().create(ApiInterface.class);

    Call<CurrencyResponse> call = apiService.getCurrencies(API_KEY);
    call.enqueue(new Callback<CurrencyResponse>() {
        @EverythingIsNonNull
        public void onResponse(Call<CurrencyResponse> call, Response<CurrencyResponse> response) {
            int statusCode = response.code();
            List<Currency> currencies = response.body().getResults();
            recyclerView.setAdapter(new CurrenciesAdapter(currencies, R.layout.list_item_currency, getApplicationContext()));
        }

        @Override
        public void onFailure(Call<CurrencyResponse> call, Throwable t) {
            // Log error here since request failed
            Log.e(TAG, t.toString());
        }
    });
}
}

我在 MainActivity 的 63 行有 NPE。

Logcat:

  --------- beginning of crash
  2019-03-11 13:58:12.020 3325-3325/com.example.mojpierwszyrest 
  E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.example.mojpierwszyrest, PID: 3325
  java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.mojpierwszyrest.model.CurrencyResponse.getResults()' on a null object reference
    at com.example.mojpierwszyrest.acitivity.MainActivity$1.onResponse(MainActivity.java:63)
    at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:71)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run
    (RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
    2019-03-11 13:58:12.563 3325-3325/com.example.mojpierwszyrest I/Process: 
    Sending signal. PID: 3325 SIG: 9

【问题讨论】:

  • 哪里有 NPE?在哪一行?你会分享堆栈跟踪(来自异常)吗?
  • 显示您的适配器代码并发布您的堆栈跟踪信息
  • 根据 API 响应(来自您给定的链接)不需要 CurrencyResponse 类。只需在您的 API 接口中使用 List&lt;Currency&gt;
  • @Basi ,上市完成

标签: android json retrofit pojo


【解决方案1】:

我检查了您在描述中提供的上述链接,我知道有一个数组作为响应。所以根据你不应该需要CurrencyResponse 类。只需Currency 类就足够了。

在你的改造界面中,api 方法应该返回currency 的列表。例如List&lt;Currency&gt; getCurrencyList()。它应该可以工作。

对于 NPE,可能的原因应该是您试图从这些类中访问一个不在 api 响应中的字段,因此该字段将为 null 并且访问该字段将引发 NPE。您可以检查堆栈跟踪以找出哪个字段访问正在引发 NPE,或者您可以分享 stacktrace 以便该社区可以帮助您。

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 2021-08-25
    • 2018-07-24
    • 2014-04-12
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多