在Android中返回null的改进响应

时间:2017-12-23 04:55:55

标签: android retrofit

我想显示JSON值的文字。我正在使用Retrofit拨打API电话我不知道我是否正确行事。无论如何这是我的代码。

以下是网址链接:http://api.icndb.com/jokes/random

网站每次都会显示一个随机笑话。以下是网站输出的示例:

{ "type": "success", "value": { "id": 175, "joke": "When Chuck Norris was a baby, he didn't suck his mother's breast. His mother served him whiskey, straight out of the bottle.", "categories": [] } } 

fragment.java

    String url = "http://api.icndb.com/";

    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.build();

    RetroFitHelper client = retrofit.create(RetroFitHelper.class);
    Call<Api> call = client.findJoke("random");

    call.enqueue(new Callback<Api>() {
        @Override
        public void onResponse(Response<Api> response, Retrofit retrofit) {

            String result = response.body().getJoke();

            Toast.makeText(getContext()," The word is: " + result ,Toast.LENGTH_LONG).show();
        }

        @Override
        public void onFailure(Throwable t) {
            Toast.makeText(getContext()," Error..." ,Toast.LENGTH_LONG).show();

        }
    });

RetroFitHelper.java

public interface RetroFitHelper {

    @GET("/jokes/{random}")
    Call<Api> findJoke(@Path("random") String random);

}

模型类

public class Api {

    @SerializedName("joke")
    private String joke;

    public String getJoke() {
        return joke;
    }

    public void setJoke(String joke){
        this.joke = joke;
    }
}

4 个答案:

答案 0 :(得分:8)

提供的json响应在另一个json对象中有一个名为value的json对象(形式为{..,"value":{}})。所以我们需要两个模型类 - 一个用于outer json object,另一个用于inner json object(值)。

您需要有两个这样的模型类

public class Api {

@SerializedName("type")
@Expose
private String type;
@SerializedName("value")
@Expose
private Value value;

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public Value getValue() {
return value;
}

public void setValue(Value value) {
this.value = value;
}

和以下值对象

public class Value {

@SerializedName("id")
@Expose
private Integer id;
@SerializedName("joke")
@Expose
private String joke;
@SerializedName("categories")
@Expose
private List<Object> categories = null;

public Integer getId() {
return id;
}

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

public String getJoke() {
return joke;
}

public void setJoke(String joke) {
this.joke = joke;
}

public List<Object> getCategories() {
return categories;
}

public void setCategories(List<Object> categories) {
this.categories = categories;
}

}

现在,response.body()的结果为outer json object(Api)response.body().getValue()的结果为inner json object(Value)

现在在你的回复回调中,得到这样的回复

String result = response.body().getValue().getJoke();
  

另外,请确保您在清单中声明了必要的互联网权限,例如

<uses-permission android:name="android.permission.INTERNET" />

  

确保您在 app level build.gradle文件中设置了最新的依赖项

implementation 'com.squareup.retrofit2:retrofit:2.4.0'

implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

答案 1 :(得分:3)

正如@Aswin建议和@Navneet回答你的POJO课有问题。 我建议您使用jsonschema2pojoRoboPOJOGenerator,以便下次避免遇到此类错误。

步骤

1)转到http://www.jsonschema2pojo.org/

2)在此处粘贴您的回复并输入包裹和类名

3)选择目标语言为Java或Kotlin(如果您正在使用)

4)源类型为Json

5)注释样式为Gson

6)单击预览

7)将这些类复制并粘贴到您的应用包

答案 2 :(得分:2)

他们正在使用的模型类中存在问题。

api的回应是:

{
"type": "success",
"value": {
    "id": 429,
    "joke": "Chuck Norris has never been accused of murder because his roundhouse kicks are recognized as &quot;acts of God.&quot;",
    "categories": []
}
}

因此,为了从响应中获取笑话的值作为字符串,您的模型类应该是这样的:

public class Api implements Serializable {

@SerializedName("type")
@Expose
private String type;
@SerializedName("value")
@Expose
private Value value;

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public Value getValue() {
    return value;
}

public void setValue(Value value) {
    this.value = value;
}
}

您的价值等级是:

public class Value implements Serializable
{
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("joke")
@Expose
private String joke;
@SerializedName("categories")
@Expose
private List<Object> categories = null;

public Integer getId() {
    return id;
}

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

public String getJoke() {
    return joke;
}

public void setJoke(String joke) {
    this.joke = joke;
}

public List<Object> getCategories() {
    return categories;
}

public void setCategories(List<Object> categories) {
    this.categories = categories;
}
}

现在你可以得到这样的价值:

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

            if (response.isSuccessful()) {
                String jokeValue = response.body().getValue().getJoke();
            }
        }

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

            t.printStackTrace();
        }
    });

根据您的要求进行更改。

快乐编码..

答案 3 :(得分:1)

AndroidManifest.xml

中添加此权限
<uses-permission android:name="android.permission.INTERNET" />

build.gradle (Module:app)

中添加此内容
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.google.code.gson:gson:2.8.2'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'

添加此界面

public interface ApiInterface {
public static final String BASE_URL = "http://api.icndb.com";

@GET("/jokes/{random}")
Call<Api> GetApiResponse(@Path("random") String random);


public class ApiClient {
    public static ApiInterface apiInterface;

    public static ApiInterface getApiInterface() {
        if (apiInterface == null) {
            Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
            apiInterface = retrofit.create(ApiInterface.class);
            return apiInterface;
        } else {
            return apiInterface;
        }
    }

}


}

创建2个模型类:com.example.app.Api.java

package com.example.app;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Api {

@SerializedName("type")
@Expose
 private String type;
@SerializedName("value")
 @Expose
 private Value value;

 public String getType() {
 return type;
 }

public Value getValue() {
return value;
}

}

创建价值模型类:com.example.app.Value.java

package com.example.app;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Value {

@SerializedName("id")
@Expose
private Integer id;
@SerializedName("joke")
@Expose
private String joke;

public int getId() {
return id;
}

public String getJoke() {
return joke;
}

}

在您的活动onCreate()方法

中添加此代码
  ApiInterface.ApiClient.getApiInterface().GetApiResponse('random').enqueue(new Callback<Api>() {
                @Override
                public void onResponse(Call<Api> call, Response<Api> response) {
                  String Joke=response.body.getValue().getJoke();
                    Toast.makeText(MainActivity.this, Joke, Toast.LENGTH_SHORT).show();
                }

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

                }
            });
相关问题