gson 如何通过改进处理来自服务器的多种类型响应

owfi6suc  于 2022-11-06  发布在  其他
关注(0)|答案(2)|浏览(169)

我使用retrofit从API获得响应,但我从同一个API获得了不同类型的响应,如

  1. JSON对象
    1.字符串类型
    1.布尔类型
    根据不同的情况,它会从同一个API给出不同类型的响应。
    我试着用这个代码:
  1. serverUtilities.getBaseClassService(getApplicationContext(), "").forgotPasswordSecurityAnswerCheck(in, new Callback<JsonObject>() {
  2. @Override
  3. public void success(JsonObject s, retrofit.client.Response response) {
  4. Log.d("forgot_password_respons", "--->" + "" + s.toString());
  5. /* to retrieve the string or integer values*/
  6. if (s.toString().equals("5")) {
  7. utilities.ShowAlert("selected wrong question", "Forgot Password SecQues");
  8. }
  9. if (s.toString().equals("1")) {
  10. // some alert here
  11. }
  12. /* to retrieve the boolean values*/
  13. if (s.toString().equals("false")) {
  14. utilities.ShowAlert(getResources().getString(R.string.otp_fail), "Forgot Password SecQues");
  15. }
  16. if (s.toString().equals("1")) {
  17. utilities.ShowAlert("Email already registered", "Social Registration");
  18. }
  19. /*to retrieve the Json object*/
  20. else
  21. if (s.toString().charAt(0) == '{') {
  22. Log.d("my_first_char", "" + s.toString().charAt(0));
  23. try {
  24. if (s.toString().contains("memberId")) {
  25. String MemberId = s.get("memberId").getAsString();
  26. String optId = s.get("otpId").getAsString();
  27. Log.d("Forgot_pass_ques_act", "" + MemberId + "--->" + optId);
  28. Singleton.setSuccessId(MemberId);
  29. Singleton.setOptId(optId);
  30. Intent intent = new Intent(ForgotPasswordQuestionActivity.this, PasswordActivity.class);
  31. startActivity(intent);
  32. Toast.makeText(ForgotPasswordQuestionActivity.this, "congrats!! second step Success ", Toast.LENGTH_SHORT).show();
  33. } else if (s.toString().contains("mId")) {
  34. }
  35. } catch (Exception e) {
  36. utilities.ShowAlert(e.getMessage(), "forgot passwordQues(catch)");
  37. Log.d("forgot_password_error", "" + e.getMessage());
  38. }
  39. // Singleton.setSuccessId(s);
  40. }
  41. }
  42. @Override
  43. public void failure(RetrofitError error) {
  44. utilities.ShowAlert(error.getMessage(), "forgot passwordQues(server)");
  45. Log.d("forgot_passwo_secAnser", "--->" + error.getMessage());
  46. }
  47. });

在这里,我在回调中将返回类型保留为“jsonObject”,并转换为 string,检查它是JsonObject还是booleanString,然后执行与之相关的操作。
但在处理响应时出现了以下异常:
回应:

  1. com.google.gson.JsonSyntaxException:Expected a com.google.gson.JsonObject but was com.google.gson.JsonPrimitive

有人能建议我如何处理这些响应在单一类型的回调改造?
如果我使用String类型作为回调函数,如下所示:

  1. server_utilities.getBaseClassService(getApplicationContext(), "").forgotPasswordResponse(in, new Callback<String>() {
  2. @Override
  3. public void success(String s, retrofit.client.Response response) {
  4. Log.d("forgot password resp", "--->" + "" + s.toString());
  5. }
  6. @Override
  7. public void failure(RetrofitError error) {
  8. Log.d("forgot_password_error", "--->" + error.getMessage());
  9. }
  10. });
  11. }

我收到此错误:

  1. com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2 path $
oymdgrw7

oymdgrw71#

服务器不能给予布尔对象,Retrofit会自动将String转换为JSONObject,因为这是您告诉它的类型
要停止这种情况,只需请求一个字符串,并在以后解析它

  1. new Callback<String>()

或者也许

  1. new Callback<JsonPrimitive>()

您还可以获取response.raw属性(在Retrofit 2.x中)

lawou6xi

lawou6xi2#

将标记类型声明为Object
@SerializedName("response") @Expose public Object response;,并在获得响应后检查类型并相应地转换为

  1. if (response.body().response!=null && response.body().response instanceof Collection<?>) {
  2. //if you find response type is collection then convert to json then json to real collection object
  3. String responseStr = new Gson().toJson(data.diagnosis.provisionalDiagnosis);
  4. Type type=new TypeToken<List<Response>>(){}.getType();
  5. List<Response> responseList=new Gson().fromJson(responseStr,type);
  6. if(responseList.size() > 0){
  7. patientInfoBinding.phoneTv.setText(responseList.get(0).phnNo);
  8. }
  9. }else if (response.body() instanceof String){
  10. String res=response.body();
  11. }else {}

像上面一样,您可以检查instanceof String/instanceof Boolean

相关问题