我使用retrofit从API获得响应,但我从同一个API获得了不同类型的响应,如
- JSON对象
1.字符串类型
1.布尔类型
根据不同的情况,它会从同一个API给出不同类型的响应。
我试着用这个代码:
serverUtilities.getBaseClassService(getApplicationContext(), "").forgotPasswordSecurityAnswerCheck(in, new Callback<JsonObject>() {
@Override
public void success(JsonObject s, retrofit.client.Response response) {
Log.d("forgot_password_respons", "--->" + "" + s.toString());
/* to retrieve the string or integer values*/
if (s.toString().equals("5")) {
utilities.ShowAlert("selected wrong question", "Forgot Password SecQues");
}
if (s.toString().equals("1")) {
// some alert here
}
/* to retrieve the boolean values*/
if (s.toString().equals("false")) {
utilities.ShowAlert(getResources().getString(R.string.otp_fail), "Forgot Password SecQues");
}
if (s.toString().equals("1")) {
utilities.ShowAlert("Email already registered", "Social Registration");
}
/*to retrieve the Json object*/
else
if (s.toString().charAt(0) == '{') {
Log.d("my_first_char", "" + s.toString().charAt(0));
try {
if (s.toString().contains("memberId")) {
String MemberId = s.get("memberId").getAsString();
String optId = s.get("otpId").getAsString();
Log.d("Forgot_pass_ques_act", "" + MemberId + "--->" + optId);
Singleton.setSuccessId(MemberId);
Singleton.setOptId(optId);
Intent intent = new Intent(ForgotPasswordQuestionActivity.this, PasswordActivity.class);
startActivity(intent);
Toast.makeText(ForgotPasswordQuestionActivity.this, "congrats!! second step Success ", Toast.LENGTH_SHORT).show();
} else if (s.toString().contains("mId")) {
}
} catch (Exception e) {
utilities.ShowAlert(e.getMessage(), "forgot passwordQues(catch)");
Log.d("forgot_password_error", "" + e.getMessage());
}
// Singleton.setSuccessId(s);
}
}
@Override
public void failure(RetrofitError error) {
utilities.ShowAlert(error.getMessage(), "forgot passwordQues(server)");
Log.d("forgot_passwo_secAnser", "--->" + error.getMessage());
}
});
在这里,我在回调中将返回类型保留为“jsonObject”,并转换为 string,检查它是JsonObject还是boolean或String,然后执行与之相关的操作。
但在处理响应时出现了以下异常:
回应:
com.google.gson.JsonSyntaxException:Expected a com.google.gson.JsonObject but was com.google.gson.JsonPrimitive
有人能建议我如何处理这些响应在单一类型的回调改造?
如果我使用String类型作为回调函数,如下所示:
server_utilities.getBaseClassService(getApplicationContext(), "").forgotPasswordResponse(in, new Callback<String>() {
@Override
public void success(String s, retrofit.client.Response response) {
Log.d("forgot password resp", "--->" + "" + s.toString());
}
@Override
public void failure(RetrofitError error) {
Log.d("forgot_password_error", "--->" + error.getMessage());
}
});
}
我收到此错误:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2 path $
2条答案
按热度按时间oymdgrw71#
服务器不能给予布尔对象,Retrofit会自动将String转换为JSONObject,因为这是您告诉它的类型
要停止这种情况,只需请求一个字符串,并在以后解析它
或者也许
您还可以获取
response.raw
属性(在Retrofit 2.x中)lawou6xi2#
将标记类型声明为
Object
@SerializedName("response") @Expose public Object response;
,并在获得响应后检查类型并相应地转换为像上面一样,您可以检查
instanceof String/instanceof Boolean