使用Retrofit库获取简单的JSON对象响应

Muh*_*mar 7 android json retrofit

我有一个带有JSON响应的Web查询:

{
    "status":true,
    "result":
      {
        "id":"1",
        "name":"ABC 1",
        "email":"info@ABc.dcom",
        "password":"123456",
        "status":false,
        "created":"0000-00-00 00:00:00"
      },
    "message":"Login successfully"
}
Run Code Online (Sandbox Code Playgroud)

我使用以下代码:

@GET("/stockers/login")
public void login(
        @Query("email") String email,
        @Query("password") String password,
        Callback<JSONObject> callback);
Run Code Online (Sandbox Code Playgroud)

在Debugger中,由Retrofit库进行的查询是正确的,但是我得到了一个空的JSON作为响应.

ApiManager.getInstance().mUrlManager.login(
        email.getText().toString().trim(),
        password.getText().toString().trim(),
        new Callback<JSONObject>()
        {
            @Override
            public void success(JSONObject jsonObj, Response response)
            {
                mDialog.dismiss();
Run Code Online (Sandbox Code Playgroud)

小智 11

只需使用JsonElementinsted JSONobject.喜欢:

@GET("/stockers/login")
Call<JsonElement> getLogin(
    @Query("email") String email,
    @Query("password") String password
);
Run Code Online (Sandbox Code Playgroud)


Ste*_*han 10

对于 Retrofit 1,如果您使用的是 Retrofit 2 并且不想使用转换器,那么您必须使用ResponseBody.

@GET("/stockers/login")
public void login(
    @Query("email") String email,
    @Query("password") String password,
    Callback<ResponseBody> callback);
Run Code Online (Sandbox Code Playgroud)

然后在您的回调中onResponse调用string主体的方法并从中创建一个 JSONObject。

if(response.isSuccessful())
    JSONObject json = new JSONObject(response.body().string());
Run Code Online (Sandbox Code Playgroud)


nic*_*sso 7

您可以使用使用Response类的Retrofit基本回调而不是Callback with JSONObject类,然后,一旦获得响应,就必须从中创建JSONObject.

请参阅:https: //stackoverflow.com/a/30870326/2037304

否则,您可以创建自己的模型类来处理响应.

首先是Result类:

public class Result {
    public int id;
    public String name;
    public String email;
    public String password;
    public boolean status;
    public Date created;
}
Run Code Online (Sandbox Code Playgroud)

然后你的响应类与Retrofit一起使用

public class MyResponse {
    public boolean status;
    public Result result;
    public String message;
}
Run Code Online (Sandbox Code Playgroud)

现在你可以打电话:

 @GET("/stockers/login") 
 public void login( 
    @Query("email") String email,
    @Query("password") String password,
    Callback<MyResponse> callback);
Run Code Online (Sandbox Code Playgroud)


ozi*_*iem 6

您可以创建如下所示的自定义工厂或从此处复制它: https: //github.com/marcinOz/Retrofit2JSONConverterFactory

public class JSONConverterFactory extends Converter.Factory {
    public static JSONConverterFactory create() {
        return new JSONConverterFactory();
    }

    private JSONConverterFactory() {
    }

    @Override public Converter<?, RequestBody> requestBodyConverter(Type type,
                                                                    Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        if (type == JSONObject.class
                || type == JSONArray.class) {
            return JSONRequestBodyConverter.INSTANCE;
        }
        return null;
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
                                                            Retrofit retrofit) {
        if (type == JSONObject.class) {
            return JSONResponseBodyConverters.JSONObjectResponseBodyConverter.INSTANCE;
        }
        if (type == JSONArray.class) {
            return JSONResponseBodyConverters.JSONArrayResponseBodyConverter.INSTANCE;
        }
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)
public class JSONRequestBodyConverter<T> implements Converter<T, RequestBody> {
    static final JSONRequestBodyConverter<Object> INSTANCE = new JSONRequestBodyConverter<>();
    private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain; charset=UTF-8");

    private JSONRequestBodyConverter() {
    }

    @Override public RequestBody convert(T value) throws IOException {
        return RequestBody.create(MEDIA_TYPE, String.valueOf(value));
    }
}
Run Code Online (Sandbox Code Playgroud)
public class JSONResponseBodyConverters {
    private JSONResponseBodyConverters() {}

    static final class JSONObjectResponseBodyConverter implements Converter<ResponseBody, JSONObject> {
        static final JSONObjectResponseBodyConverter INSTANCE = new JSONObjectResponseBodyConverter();

        @Override public JSONObject convert(ResponseBody value) throws IOException {
            try {
                return new JSONObject(value.string());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    static final class JSONArrayResponseBodyConverter implements Converter<ResponseBody, JSONArray> {
        static final JSONArrayResponseBodyConverter INSTANCE = new JSONArrayResponseBodyConverter();

        @Override public JSONArray convert(ResponseBody value) throws IOException {
            try {
                return new JSONArray(value.string());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 无论谁否决了这个答案,你都应该发表评论解释原因。我认为这是一个非常好的答案。+1。 (3认同)