get the data from web service response in retrofit android

三世轮回 提交于 2021-02-08 11:52:26

问题


i am working on retrofit from four days. I learnt how to get the data from web service but now i stuck with this response. please any one tell me how to get the data from web service. how to get the operator id,operator, RechareTypes array of strings. Please any one help me. Thanks in advance.

my code: operator:

public class Operator {
    @Expose
    private String OperatorID="";
    @Expose
    private String ServiceTypeID="";

    public String getServiceTypeID() {
        return ServiceTypeID;
    }

    public void setServiceTypeID(String serviceTypeID) {
        ServiceTypeID = serviceTypeID;
    }

    public String getOperatorID() {
        return OperatorID;
    }

    public void setOperatorID(String operatorID) {
        OperatorID = operatorID;
    }

    public String getOperatorname() {
        return operatorname;
    }

    public List<Operators> getOrderItems() {
        return OrderItems;
    }

    public void setOrderItems(List<Operators> orderItems) {
        OrderItems = orderItems;
    }

    public void setOperatorname(String operatorname) {
        this.operatorname = operatorname;
    }

    @Expose

    private String operatorname="";
    @Expose
    private List<Operators> OrderItems = new ArrayList<Operators>();
    public Operator(){

    }
}

operators:

public class Operators {
   private  String RechargeTypeID="";

    public String getRechargeType() {
        return RechargeType;
    }

    public void setRechargeType(String rechargeType) {
        RechargeType = rechargeType;
    }

    public String getSMSCode() {
        return SMSCode;
    }

    public void setSMSCode(String SMSCode) {
        this.SMSCode = SMSCode;
    }

    public String getRechargeTypeID() {
        return RechargeTypeID;
    }

    public void setRechargeTypeID(String rechargeTypeID) {
        RechargeTypeID = rechargeTypeID;
    }

    private String RechargeType="";
    private String SMSCode="";
}

activity:

ArrayList<Operator> operator;

    void executeCircleAndOperatorsList() {
            db.ClearTables();
            ServiceClient serviceClient = ServiceUtil.getServiceClient();

            JsonParser jsonParser = new JsonParser();

            serviceClient.getOperators("getRecharge_Operator_v2", operatorCallback);

        }

Callback<JsonObject> operatorCallback = new Callback<JsonObject>() {

        @Override
        public void success(final JsonObject jsonObject, Response response) {
            parseoperators(jsonObject);
            Thread t=new Thread(new Runnable() {
                @Override
                public void run() {
                    parseoperators(jsonObject);
                }
            });
            t.start();
        }

        @Override
        public void failure(RetrofitError error) {

        }
    };
  public void parseoperators(JsonObject result) {
      if(result.has("Status")){
          try{
              String Status = result.get("Status")
                      .getAsString();
              if (Status.equals("1")) {
                  Gson gson = new Gson();
                  JsonArray array = result.get(
                          "data").getAsJsonArray();
                  Log.v("TAG_CIRCLELIST", "" + array);
                  Type type = new TypeToken<ArrayList<Operator>>() {
                  }.getType();

                  operator.addAll((Collection<? extends Operator>) gson
                          .fromJson(array, type));




              }
              else {
                  throw new JSONException("Something went wrong ");
              }
          }
          catch(JSONException e){

          }

      }



    }

json:

{
    "Status": 1,
    "data": [
        {
            "ServiceTypeID": 1,
            "OperatorID": 1,
            "Operator": "Airtel",
            "RechareTypes": [
                {
                    "RechargeTypeID": 1,
                    "RechargeType": "Topup",
                    "SMSCode": "AIRT"
                }
            ]
        },
        {
            "ServiceTypeID": 1,
            "OperatorID": 2,
            "Operator": "BSNL",
            "RechareTypes": [
                {
                    "RechargeTypeID": 2,
                    "RechargeType": "Topup",
                    "SMSCode": "BSNL"
                },
                {
                    "RechargeTypeID": 3,
                    "RechargeType": "Special",
                    "SMSCode": "BSNLSPL"
                }
            ]
        },
        {
            "ServiceTypeID": 1,
            "OperatorID": 3,
            "Operator": "Aircel",
            "RechareTypes": [
                {
                    "RechargeTypeID": 4,
                    "RechargeType": "Topup",
                    "SMSCode": "AIRC"
                }
            ]
        },
        {
            "ServiceTypeID": 1,
            "OperatorID": 4,
            "Operator": "Idea",
            "RechareTypes": [
                {
                    "RechargeTypeID": 5,
                    "RechargeType": "Topup",
                    "SMSCode": "IDEA"
                }
            ]
          }
    ]
}

回答1:


Retrofit uses Gson by default to convert HTTP bodies to and from JSON

create the operator pojo as follows

public class Operators {

    @Expose
    private String Status;
    @Expose
    private List<Operator> data = new ArrayList<Operator>();

    public String getStatus() {
        return Status;
    }

    public void setStatus(String Status) {
        this.Status = Status;
    }

    public List<Operator> getData() {
        return data;
    }

    public void setData(List<Operator> data) {
        this.data = data;
    }
}

class Operator {

    @Expose
    private String ServiceTypeID;
    @Expose
    private String OperatorID;
    @Expose
    private String Operator;
    @Expose
    private List<RechareType> RechareTypes = new ArrayList<RechareType>();

    public String getServiceTypeID() {
        return ServiceTypeID;
    }

    public void setServiceTypeID(String ServiceTypeID) {
        this.ServiceTypeID = ServiceTypeID;
    }

    public String getOperatorID() {
        return OperatorID;
    }

    public void setOperatorID(String OperatorID) {
        this.OperatorID = OperatorID;
    }

    public String getOperator() {
        return Operator;
    }

    public void setOperator(String Operator) {
        this.Operator = Operator;
    }

    public List<RechareType> getRechareTypes() {
        return RechareTypes;
    }

    public void setRechareTypes(List<RechareType> RechareTypes) {
        this.RechareTypes = RechareTypes;
    }

}

class RechareType {

    @Expose
    private String RechargeTypeID;
    @Expose
    private String RechargeType;
    @Expose
    private String SMSCode;

    public String getRechargeTypeID() {
        return RechargeTypeID;
    }

    public void setRechargeTypeID(String RechargeTypeID) {
        this.RechargeTypeID = RechargeTypeID;
    }

    public String getRechargeType() {
        return RechargeType;
    }

    public void setRechargeType(String RechargeType) {
        this.RechargeType = RechargeType;
    }

    public String getSMSCode() {
        return SMSCode;
    }

    public void setSMSCode(String SMSCode) {
        this.SMSCode = SMSCode;
    }

}

Update "void executeCircleAndOperatorsList()" to

void executeCircleAndOperatorsList() {
    db.ClearTables();
    ServiceClient serviceClient = ServiceUtil.getServiceClient();
    Callback<Operators> callback = new Callback<Operators>() {
    @Override
    public void failure(RetrofitError arg0) {
    }
    @Override
    public void success(Operators operatorList, Response arg1) {
        if(operatorList.getStatus().equalsIgnoreCase("1")){
                Log.d("Operator_ID", operatorList.getData().get(0).getOperatorID());    
            }
        }
    };
    serviceClient.getOperators("getRecharge_Operator_v2", callback);
}   

update getoperators method signature accordingly to add callback Callback<Operators> cb

 void getOperators(Callback<Operators> cb); 



回答2:


Best practice to use Retrofit

Compile this libraries for Retrofit and GSON

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

RequestInterface for all webservices (POST/GET)

public interface RequestInterface {

@POST("/api/postUserdata")
Call<Boolean> addUserData(@Body User user);


@GET("/api/getAllUsers")
Call<List<Data>> getAllUsersDetails();

@POST("/api/isEmailExist")
Call<Boolean> isEmailExist(@Path("Email") String Email);

}

CommonHelper class for Webservice client API

public class CommonHelper {

public RequestInterface service;
public String BASE_URL = "your base url";

public RequestInterface getRetrofitInstance() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    service = retrofit.create(RequestInterface.class);
    return service;
}

public boolean isConnectingToInternet(Context _context) {
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null)
            for (int i = 0; i < info.length; i++)

                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }

    }
    return false;
}
}

Call Web service in Activity

public void getDataFromServer() {

    mProgressDialog = new ProgressDialog(getActivity());
    mProgressDialog.setIndeterminate(true);
    mProgressDialog.setCancelable(false);
    mProgressDialog.setTitle("Loading");
    mProgressDialog.setMessage("Getting data...");


  CommonHelper commonHeloper = new CommonHelper();

  Call<List<Data>> call= commonHelper.getRetrofitInstance().getAllUsersDetails();


  call.enqueue(new Callback<List<Data>>() {
        @Override
        public void onResponse(Response<List<Data>> response, Retrofit retrofit) {
            mProgressDialog.dismiss();



        }

        @Override
        public void onFailure(Throwable t) {
            t.printStackTrace();
            mProgressDialog.dismiss();
        }
    });
}


来源:https://stackoverflow.com/questions/32153570/get-the-data-from-web-service-response-in-retrofit-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!