改造2:从响应机构获取JSON

Dir*_*rus 52 android json retrofit retrofit2

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

这就是我的json的样子

{"id":1,"Username":"admin","Level":"Administrator"}
Run Code Online (Sandbox Code Playgroud)

这是我的API

@FormUrlEncoded
@POST("/api/level")
Call<ResponseBody> checkLevel(@Field("id") int id);
Run Code Online (Sandbox Code Playgroud)

这就是我的代码的样子

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) {
            }
        });
Run Code Online (Sandbox Code Playgroud)

我是新手改造2并使用上面的代码,它总是让我的应用程序崩溃因为response.body().toString()返回null.

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

sus*_*dlh 46

使用此链接将您的JSON转换为POJO,并使用下图中选择的选项

在此输入图像描述

你会得到一个像你这样的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;
    }

}
Run Code Online (Sandbox Code Playgroud)

并使用这样的界面:

@FormUrlEncoded
@POST("/api/level")
Call<Result> checkLevel(@Field("id") int id);
Run Code Online (Sandbox Code Playgroud)

并像这样打电话:

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

    }
});
Run Code Online (Sandbox Code Playgroud)

并在gradale中使用依赖项

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.+'
Run Code Online (Sandbox Code Playgroud)

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


Sun*_*nil 38

如果您想以JSON格式获得完整响应,请尝试以下方法:

我尝试了一种新方法,以JSON格式从服务器获取完整响应,而无需创建任何模型类.我没有使用任何模型类从服务器获取数据,因为我不知道我将得到什么响应,或者它可能根据要求而改变.

这是JSON响应:

{"contacts": [
    {
        "id": "c200",
        "name": "sunil",
        "email": "email@gmail.com",
        "address": "xx-xx-xxxx,x - street, x - country",
        "gender" : "male",
        "phone": {
            "mobile": "+91 0000000000",
            "home": "00 000000",
            "office": "00 000000"
        }
    },
    {
        "id": "c201",
        "name": "Johnny Depp",
        "email": "johnny_depp@gmail.com",
        "address": "xx-xx-xxxx,x - street, x - country",
        "gender" : "male",
        "phone": {
            "mobile": "+91 0000000000",
            "home": "00 000000",
            "office": "00 000000"
        }
    },
    .
    .
    .
]}
Run Code Online (Sandbox Code Playgroud)
  1. 在API界面中更改参数

    public interface ApiInterface {
    @POST("/index.php/User/login")//your api link 
    @FormUrlEncoded
    Call<Object> getmovies(@Field("user_email_address") String title,
                    @Field("user_password") String body);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在你主要活动中你打电话给这个

    ApiInterface apiService =
            ApiClient.getClient().create(ApiInterface.class);
    
    Call call = apiService.getmovies("a@gmail.com","123456");
    call.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) {
            Log.e("TAG", "response 33: "+new Gson().toJson(response.body()) );
        }
    
        @Override
        public void onFailure(Call call, Throwable t) {
            Log.e("TAG", "onFailure: "+t.toString() );
            // Log error here since request failed
        }
    });
    
    Run Code Online (Sandbox Code Playgroud)
  3. 之后,您通常可以使用JSON对象和JSON数组获取参数

产量 在此输入图像描述


And*_*ath 21

用它来获取String

String res = response.body().string();
Run Code Online (Sandbox Code Playgroud)

代替

String res = response.body().toString();
Run Code Online (Sandbox Code Playgroud)

并且在将responsebody转换为字符串之前始终检查null

if(response.body() != null){
     //do your stuff   
}
Run Code Online (Sandbox Code Playgroud)

  • 这不起作用......响应主体是一个一次性值,只能消耗一次所以在调试时有一个来自检查员的“幕后”调用,并且主体总是空的。 (2认同)

Kri*_*hna 7

你可以像这样使用它。

 public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            if (response.isSuccessful()) {
                try {
                    JSONObject jsonObject = new JSONObject(new Gson().toJson(response.body()));
                    msg = jsonObject.getString("msg");
                    status = jsonObject.getBoolean("status");

                    msg = jsonObject.getString("msg");
                    status = jsonObject.getBoolean("status");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                Log.e("cvbnop",response.body().toString());
            } else {
                Toast.makeText(MainActivity.this, "Some error occurred...", Toast.LENGTH_LONG).show();
            }
        }
Run Code Online (Sandbox Code Playgroud)


Mor*_*ard 7

我发现其他答案的组合有效:

interface ApiInterface {
    @GET("/someurl")
    Call<ResponseBody> getdata()
}

apiService.getdata().enqueue(object : Callback {
    override fun onResponse(call: Call, response: Response) {
        val rawJsonString = response.body()?.string()
    }
})
Run Code Online (Sandbox Code Playgroud)

重要的部分是响应类型应该是ResponseBody并用于response.body()?.string()获取原始字符串。

/sf/answers/2330027871/


小智 5

add dependency for retrofit2

compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
Run Code Online (Sandbox Code Playgroud)

create class for base url

public class ApiClient     
{
public static final String BASE_URL = "base_url";

private static Retrofit retrofit = null;

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

}
Run Code Online (Sandbox Code Playgroud)

after that create class model to get value

public class ApprovalModel {

@SerializedName("key_parameter")
private String approvalName;
public String getApprovalName() {
    return approvalName;
}
}
Run Code Online (Sandbox Code Playgroud)

create interface class

public interface ApiInterface { 
@GET("append_url")
Call<CompanyDetailsResponse> getCompanyDetails();
}
Run Code Online (Sandbox Code Playgroud)

after that in main class

 if(Connectivity.isConnected(mContext)){
            final ProgressDialog mProgressDialog = new ProgressDialog(mContext);
            mProgressDialog.setIndeterminate(true);
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.show();

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

            Call<CompanyDetailsResponse> call = apiService.getCompanyDetails();
            call.enqueue(new Callback<CompanyDetailsResponse>() {
                @Override
                public void onResponse(Call<CompanyDetailsResponse>call, Response<CompanyDetailsResponse> response) {
                    mProgressDialog.dismiss();
                    if(response!=null && response.isSuccessful()) {
                        List<CompanyDetails> companyList = response.body().getCompanyDetailsList();

                        if (companyList != null&&companyList.size()>0) {
                            for (int i = 0; i < companyList.size(); i++) {
                                Log.d(TAG, "" + companyList.get(i));
                            }
                         //get values
                        }else{
                            //show alert not get value
                        }
                    }else{
                        //show error message

                    }
                }

                @Override
                public void onFailure(Call<CompanyDetailsResponse>call, Throwable t) {
                    // Log error here since request failed
                    Log.e(TAG, t.toString());
                    mProgressDialog.dismiss();
                }
            });
        }else{
            //network error alert box

        }
Run Code Online (Sandbox Code Playgroud)