首页 > 解决方案 > 在 Android 中使用改造解析嵌套的 json

问题描述

我收到空指针异常。我想从此 Quotes Api - https://quotes.rest/中检索随机报价以显示在我的 android 应用程序中。我哪里错了?

(如果我没有正确提出问题或通过发布问题违反任何规则,我深表歉意。这是我第一次提出问题)

我已经创建了必要的 POJO 并尝试在 MainActivity 中检索报价。

    GetDataService service = RetrofitClientInstance.getRetrofitInstance().create(GetDataService.class);

    Call<Example> call = service.getRandomQuote();

    call.enqueue(new Callback<Example>() {
        @Override
        public void onResponse(Call<Example> call, Response<Example> response) {

            String quote = response.body().getContents().getQuotes().get(0).getQuote();
            Log.d(TAG, "onResponse: ************" + quote);
        }

获取数据服务

public interface GetDataService {
@GET("/quote/random")
Call<Example> getRandomQuote();
}

POJO-报价

public class Quote {

@SerializedName("quote")
private String quote;

public Quote(String quote) {
    this.quote = quote;
}

public String getQuote() {
    return quote;
}

public void setQuote(String quote) {
    this.quote = quote;
}
}

POJO- 内容

public class Contents {

@SerializedName("quotes")
@Expose
private List<Quote> quotes;


public List<Quote> getQuotes() {
    return quotes;
}

public void setQuotes(List<Quote> quotes) {
    this.quotes = quotes;
}
}

POJO-示例

public class Example {

@SerializedName("contents")
@Expose
private Contents contents;

public Contents getContents() {
    return contents;
}

public void setContents(Contents contents) {
    this.contents = contents;
}
}

RetrofitClientInstance 类

public class RetrofitClientInstance {

private static Retrofit retrofit = null;
private static  final String BASE_URL = "https://quotes.rest";

public static Retrofit getRetrofitInstance(){
    if(retrofit == null){
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}
}

我希望输出是来自此 Quotes Api ( https://quotes.rest/ ) 的随机引用,但我得到一个空指针异常。以下是错误 -

java.lang.NullPointerException: Attempt to invoke virtual method 'com.platinumstudio.contactsdemo7.network.Contents com.platinumstudio.contactsdemo7.Example.getContents()' on a null object reference
    at     com.platinumstudio.contactsdemo7.MainActivity$3.onResponse(MainActivity.java)

标签: androidjsonnullpointerexceptionretrofit2

解决方案


您在这里使用的 API 是this。正如 API 文档所说,获取数据需要 API 密钥。由于您没有在代码中添加 API 密钥,因此它应该返回带有HTTP Status Codeof的不成功响应401

最好的做法是在对接收到的数据执行操作之前检查响应是否成功,以避免应用程序中出现崩溃问题。当您从 API 获取数据时,请始终保留此代码段:

call.enqueue(new Callback<Example>() {
        @Override
        public void onResponse(Call<Example> call, Response<Example> response) {
                if(response.isSuccessful && response.body() != null){
                    //Get contents & quote
                }
                else {
                    //Check response code & show the relevant error message through Toast or Dialog
                }
        }

        @Override
        public void onFailure(Call call, Throwable t) {
                //Show a failed message to the user
        }
}

推荐阅读