当数据是字符串而不是对象时,如何在android中解析相同的json响应?
当我得到回应时,成功课程非常有效。但当它失败时,它给了我错误 数据传入URL失败时的响应:当数据是字符串而不是对象时,如何在android中解析相同的json响应?,android,json,observable,retrofit2,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"
{
"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
错误
这是不可能的。你的情况应该是这样的
{
"success": -1,
"message": "Invalid username or password",
"data": {}
}
请您的后端服务团队使用空对象对其进行更改,以便相同的响应对象可以重复使用这是不可能的。你的情况应该是这样的
{
"success": -1,
"message": "Invalid username or password",
"data": {}
}
请您的后端服务团队使用空对象对其进行更改,以便根据您的问题陈述重复使用相同的响应对象,您需要为响应创建泛型类型。而不是在UserResponse中为“data”对象键入User。类使其对象类型如下:-
@Getter
@Setter
public class UserResponseCustom{
private int success;
private String message;
private Object data;// modified for any type of data
}
在webservice调用中,检查数据是否为用户实例,仅此而已
现在您可以检查它是否为对象
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
}
根据您的问题陈述,您需要为响应创建泛型类型。而不是为UserResponse中的“data”对象创建类型User。类将其创建为如下对象类型:-
@Getter
@Setter
public class UserResponseCustom{
private int success;
private String message;
private Object data;// modified for any type of data
}
在webservice调用中,检查数据是否为用户实例,仅此而已
现在您可以检查它是否为对象
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
}
根据您的问题陈述编辑了我的答案是的,您是对的,但我不会手动将json字符串转换为类。我对库进行了改造,其中observable方法会自动解析此数据,而不是再次解析同一问题。根据您的问题陈述编辑了我的答案是的,您是对的,但我不会手动将json字符串转换为类。我对库进行了改进,其中可观测方法自动解析这些数据,而不是再次解析相同的问题。