第一个json字符串是这样的:
{
"code": "2000",
"msg": "success",
"data": {
"khmc": "some company",
"contact": "jack",
"phone": "18888888888",
"address": "Shanghai"
}
}
第二个json字符串是这样的:
{
"code": "2000",
"msg": "success",
"data": "add success"
}
服务器返回的json有两种类型,如上所述。
改装版本和rxjava版本是这样的:
//ReactiveX
compile 'io.reactivex:rxjava:1.2.3'
compile 'io.reactivex:rxandroid:1.2.1'
//Retrofit
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
在我的Android应用程序中,我使用MVP构建我的应用程序,我的片段只能有一个Presenter实例,所以在我的片段中,我使用了唯一一个Presenter实例发送两种类型的服务器API请求,仅onNext回调有一个。主要代码如下:
public class AddFormFragment extends MvpFragment<AddFormPresenter> implements IAddFormView {
@Override
public void onNext(JudiciaryHttpResult judiciaryHttpResult) {
switch (judiciaryHttpResult.code) {
case Constants.JudiciaryResponseCode.JUDICIARY_SUCCESS_CODE:
if (judiciaryHttpResult.data != null) {
Object object = judiciaryHttpResult.data;
if (object instanceof String) {
ToastUtil.showShort(object.toString());
} else {
JudiciaryUser user = (JudiciaryUser) object;
mKhmcEt.setText(user.getKhmc());
mContactEt.setText(user.getContact());
mPhoneEt.setText(user.getPhone());
mAddressEt.setText(user.getAddress());
}
}
break;
}
}
}
}
司法部门的HttpResult如下:
public class JudiciaryHttpResult<T> {
public int code;
public String msg;
public T data;
}
JudiciaryUser如下:
public class JudiciaryUser {
public String khmc;
public String contact;
public String phone;
public String address;
}
当我在我的片段中获得onNext回调时,else块的第一行代码如下所示:
JudiciaryUser user = (JudiciaryUser) judiciaryHttpResult.data;
我会像问题标题那样得到例外,任何人都可以帮助我吗?
答案 0 :(得分:0)
我认为judiciaryHttpResult.data是一个LinkedTreeMap实例,所以我可以这样做:
//JudiciaryUser user = (JudiciaryUser) judiciaryHttpResult.data;
//mKhmcEt.setText(user.khmc);
//mContactEt.setText(user.contact);
//mPhoneEt.setText(user.phone);
//mAddressEt.setText(user.address);
//region Solve java.lang.ClassCastException:
// com.google.gson.internal.LinkedTreeMap cannot be cast to
// cn.shllwl.judiciaryauther.entity.bean.JudiciaryUser
LinkedTreeMap linkedTreeMap = (LinkedTreeMap) judiciaryHttpResult.data;
mKhmcEt.setText(linkedTreeMap.get("khmc").toString());
mContactEt.setText(linkedTreeMap.get("contact").toString());
mPhoneEt.setText(linkedTreeMap.get("phone").toString());
mAddressEt.setText(linkedTreeMap.get("address").toString());
//endregion
像上面一样,代码工作正常。但我认为上面的代码不是最佳解决方案。