bug 自定义的json2bean的bug

bug

在json2bean中如果不进行转换  if(bean instanceof HttpLogin){,将调用的市父类的Json2Meß

此并非最好的解决办法,应该用官方的json.toobject

package com.xx.app.inspector.api;
import android.content.Context;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.xx.app.inspector.model.Http;
import com.xx.app.inspector.model.HttpLogin;
import com.xx.app.inspector.utils.LogUtils;
import org.json.JSONException;
import org.json.JSONObject;

 

public class HttpCallBack<T extends Http> extends RequestCallBack<String> {
    private Context mContext;
    public HttpCallBack(){}
    public HttpCallBack(Context context){
        this.mContext = context;
    }
    @Override
    public void onSuccess(ResponseInfo<String> responseInfo) {
    }
    @Override
    public void onFailure(HttpException e, String s) {
    }
    public T json2Bean(String result,T bean){
        try {
            JSONObject json = new JSONObject(result);
            if(bean instanceof HttpLogin){
                HttpLogin h= (HttpLogin)bean;
                h.json2Me(json);
            }else{
                bean.Json2Me(json);
            }
            return bean;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}
public class HttpLogin extends Http {
    private  final String TAG = "HttpLogin";
    
    public String userName;
    public Long userId;
    
    public Token token;
    
    public void json2Me(JSONObject jsonObj) throws JSONException{
        super.Json2Me(jsonObj);
        if(this.status == STATUS_SUCCESS){
            JSONObject body = jsonObj.getJSONObject("body");
            userName = body.getString("userName");
            userId = body.getLong("userId");
            LogUtils.d(TAG,"==="+userName);
            token= new Token();
            token.json2Me(body.getJSONObject("token"));
        }
    }
}

  

public class Http {
    
    /** 业务请求结果:成功*/
    public static final int STATUS_SUCCESS = 0;
    /** 业务请求结果:错误*/
    public static final int STATUS_ERROR = 1;
    
    public Integer status;
    public Integer code;
    
    public void Json2Me(JSONObject jsonObj) throws JSONException{
        JSONObject obj = jsonObj.getJSONObject("header");
        status = (Integer)obj.get("status");
        code = getInteger(obj,"status");
        code = getInteger(obj,"code");
    }
    
    
    
    protected Integer getInteger(JSONObject obj,String key) throws JSONException{
        return obj.isNull(key)?null:obj.getInt(key);
    }
    
    
    protected Long getLong(JSONObject obj,String key) throws JSONException{
        return obj.isNull(key)?null:obj.getLong(key);
    }
}

 

原文地址:https://www.cnblogs.com/stit/p/6368006.html