改造2:从响应正文获取JSON [英] Retrofit 2: Get JSON from Response body

查看:80
本文介绍了改造2:从响应正文获取JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用改造2从我的api中获取字符串json,当使用改造1来获取此json时我没有问题,但是使用改造2为我返回 null .

I want to get string json from my api using retrofit 2, I have no problem when using retrofit 1 to get this json but using retrofit 2 returns null for me.

这是我的json的样子

This is what my json looks like

{"id":1,"Username":"admin","Level":"Administrator"}

这是我的API

@FormUrlEncoded
@POST("/api/level")
Call<ResponseBody> checkLevel(@Field("id") int id);

这是我的代码的样子

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Config.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Api api = retrofit.create(Api.class);
        Call<ResponseBody> call = api.checkLevel(1);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                JsonObject post = new JsonObject().get(response.body().toString()).getAsJsonObject();
                    if (post.get("Level").getAsString().contains("Administrator")) {

                    }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });

我不熟悉翻新2并使用上面的代码,因为response.body().toString()返回null,这总是使我的应用程序崩溃.

I'm new to retrofit 2 and using above code, it always make my apps crash because response.body().toString() returns null.

请指导我如何获取json字符串,以便将其转换为JsonObject.

Please guide me on how to get that json string so I can convert it into JsonObject.

推荐答案

使用此链接到使用下图所示的选择选项将JSON转换为POJO

Use this link to convert your JSON into POJO with select options as selected in image below

您将获得一个POJO类,用于这样的响应

public class Result {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("Username")
    @Expose
    private String username;
    @SerializedName("Level")
    @Expose
    private String level;

    /**
    * 
    * @return
    * The id
    */
    public Integer getId() {
        return id;
    }

    /**
    * 
    * @param id
    * The id
    */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
    * 
    * @return
    * The username
    */
    public String getUsername() {
        return username;
    }

    /**
    * 
    * @param username
    * The Username
    */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
    * 
    * @return
    * The level
    */
    public String getLevel() {
        return level;
    }

    /**
    * 
    * @param level
    * The Level
    */
    public void setLevel(String level) {
        this.level = level;
    }

}

并使用如下界面:

@FormUrlEncoded
@POST("/api/level")
Call<Result> checkLevel(@Field("id") int id);

并按以下方式致电:

Call<Result> call = api.checkLevel(1);
call.enqueue(new Callback<Result>() {
    @Override
    public void onResponse(Call<Result> call, Response<Result> response) { 
     if(response.isSuccessful()){
        response.body(); // have your all data
        int id =response.body().getId();
        String userName = response.body().getUsername();
        String level = response.body().getLevel();
        }else   Toast.makeText(context,response.errorBody().string(),Toast.LENGTH_SHORT).show(); // this will tell you why your api doesnt work most of time

    }

    @Override
    public void onFailure(Call<Result> call, Throwable t) {
     Toast.makeText(context,t.toString(),Toast.LENGTH_SHORT).show(); // ALL NETWORK ERROR HERE

    }
});

并在Gradle中使用依赖项

and use dependencies in Gradle

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.+'

注意:发生错误,是因为您将JSON更改为POJO(在翻新中使用addConverterFactory(GsonConverterFactory.create())).如果要使用JSON响应,请从Retrofit中删除addConverterFactory(GsonConverterFactory.create()).如果没有,请使用上述解决方案

NOTE: The error occurs because you changed your JSON into POJO (by use of addConverterFactory(GsonConverterFactory.create()) in retrofit). If you want response in JSON then remove the addConverterFactory(GsonConverterFactory.create()) from Retrofit. If not then use the above solution

这篇关于改造2:从响应正文获取JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆