有没有办法使用`JSONObject`而不是`JsonObject`来从改造中读取JSON数据

时间:2018-05-02 10:10:56

标签: android performance retrofit retrofit2

我将一些参数传递给服务,并向我返回json object

我已经完成了以下工作。

@POST("testservice")
@FormUrlEncoded
Call<JsonObject> getRegisterUserData(
        @Header("x-dsn") String dsn,
        @Field("id") String id
);

On Activity class我做了以下。

    Retrofit retrofit= new Retrofit.Builder()
            .baseUrl(API.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

call.enqueue(new Callback<JsonObject>() {
    @Override
    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
        parseResponse(response);
    }

这工作正常,但问题是如果我使用JSONObject而不是com.google.JsonObject,那么我无法从服务器获得实际响应jsonObject,并返回{{1字符串。

我想在这里使用{},是否可以使用JSONObject进行改造。

2 个答案:

答案 0 :(得分:1)

为什么不创建json的模型类,并从响应中创建该类的对象,如下所示:

call.enqueue(new Callback<YourClass>() {
@Override
public void onResponse(Call<YourClass> call, Response<YourClass> response) {
    YourClass yourObject = new YourClass();
    yourObject = response.body()
}

并将YourClass.java文件创建为:

public class YourClass
{
    @SerializedName("jsonAttributeName")
    @Expose
    private int/String/boolean yourAttribute;

    // Create getter/setters
}

答案 1 :(得分:1)

如果您想使用 Retrofit 手动解析,可以在界面中传递 oKhttp ResponseBody类而不是您的模型类,如下所示

@POST("testservice")
@FormUrlEncoded
Call<ResponseBody> getRegisterUserData(
        @Header("x-dsn") String dsn,
        @Field("id") String id
);

在您的改装调用响应中,response.body().string()类对象中的JSONObject获取它,如下所示 -

 call.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        try {
                                Log.d("test", response.body().string());
                                JSONObject jsonObject = new JSONObject(response.body().string());
                            } catch (IOException e) {
                                e.printStackTrace();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
    }

response.body().string()返回一串 json 响应。

谢谢,我希望它为你工作。