使用Retrofit Json Parsing返回用户配置文件数据

时间:2017-02-16 09:53:44

标签: android json retrofit

我难以从改造中返回用户数据。我想从服务器返回数据并插入共享首选项以维护用户会话 这是来自服务器的JsonResponse

{
    "result":"success",
    "message":"Your Login was successful...Welcome",
    "bool":"true",
    "user":{
          "firstname":"Steve",
          "lastname":"Karuma",
          "phone":"0728753983",
          "natID":"29775996",
          "emailAddress":"stevekaruma@gmail.com",
          "unique_id":"589496660cd8e1.44744002"
          }
}

这是我的登录流程代码段

private void loginProcess(String phone, String password) {

    final ProgressDialog progressDialog = new ProgressDialog(Login.this);
    progressDialog.setTitle("Just a moment");
    progressDialog.setMessage("Loading....");
    progressDialog.show();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RequestInterface requestInterface = retrofit.create(RequestInterface.class);

    ShopUser user = new ShopUser();
    user.setPhone(phone);
    user.setPassword(password);
    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.LOGIN_OPERATION);
    request.setUser(user);

    Call<ServerResponse> response = requestInterface.operation(request);

    response.enqueue(new Callback<ServerResponse>() {
        @Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

            ServerResponse resp = response.body();
            Toast.makeText(getApplicationContext(),resp.getMessage(),Toast.LENGTH_LONG).show();
            Log.i(Constants.TAG,resp.getMessage());

            if(resp.getResult().equals(Constants.SUCCESS)){
                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean(Constants.IS_LOGGED_IN,true);
                editor.putString(Constants.FIRST_NAME, resp.getUser().getFirstname());
                editor.putString(Constants.LAST_NAME, resp.getUser().getLastname());
                editor.putString(Constants.EMAIL, resp.getUser().getEmail());
                editor.putString(Constants.PHONE, resp.getUser().getPhone());
                editor.putString(Constants.ID_NUMBER, resp.getUser().getNatID());
                editor.putString(Constants.UNIQUE_ID, resp.getUser().getUnique_id());
                editor.apply();
                goToProfile();

            }
            progressDialog.dismiss();

        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {

            Log.d(Constants.TAG,"Failed");
            Toast.makeText(getApplicationContext(),t.getLocalizedMessage(),Toast.LENGTH_LONG).show();
            progressDialog.dismiss();

        }
    });
}

1 个答案:

答案 0 :(得分:0)

您的ServerResponse类必须扩展Serializable以通过getter获取JSON