当数据是字符串而不是对象时,如何在android中使用解析相同的json响应?

时间:2017-07-24 11:44:13

标签: android json observable retrofit2

当我得到回应时,成功课程完美无缺。但是当它失败时它给了我错误。

在URL中传递失败数据时的响应:

{
  "success": -1,
  "message": "Invalid username or password",
  "data": ""
}

在URL中传递正确数据时的响应:

{
  "success": 1,
  "message": "User successfully logged in",
  "data": {
    "userId": 219,
    "userName": "mp",
    "picture": "219.png",
    "isBo": false,
    "isPo": true,
    "isHm": true,
    "hmProfileCompletionStatus": 3,
    "poProfileCompletionStatus": 2,
    "poPhoto": null,
    "hmPhoto": null,
    "custStripeToken": "xxx",
    "accountStripeToken": "xx",
    "bgcStatus": true,
    "idCardStatus": true,
    "isInsured": null,
    "amISponsered": false,
    "hmRating": null,
    "poRating": null,
    "email": "xxx@gmail.com"
  }
}

UserResponse.java

@Getter
@Setter
public class UserResponse{
    private int success;
    private String message;
    private User data;
}

错误

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 64 path $.data

2 个答案:

答案 0 :(得分:5)

这是不可能的。在你的情况下它应该是这样的

{
  "success": -1,
  "message": "Invalid username or password",
  "data": {}
}

请您的后端服务团队使用空对象进行更改,以便可以重复使用相同的响应对象

答案 1 :(得分:0)

根据您的问题陈述,您需要为响应设置通用类型。而不是 UserResponse.Class 中的“数据”对象的类型用户,使其成为对象这样输入: -

  @Getter
  @Setter
  public class UserResponseCustom{
  private int success;
  private String message;
  private Object data;// modified for any type of data
  }

在webservice调用上,检查数据是否是User的实例,就是这样。

现在您可以检查它是否是对象

    if (userResponseCustom.getData() instanceOf User)

 /*userResponseCustom is supposed to be object of UserResponseCustom 
 which you are getting from server*/

  {
    // it's an object

    // do whatever you want with data as User Object
   }
  else
   {
    // it is an string, handle it
   }