2

Hello I am looking the way to not setting all values from POJO class one by one. and setter must be invoked in one go.

I have this POJO data.

private int id;
private String newsfeedCategories;
private String lastName;
private String email;
private String mobile;
private String sendNotifications;
private String zipcode;
private String uniounSupplier;
private String unionContractor;
private String password;
private String lastUpdate;
private String deviceType;
private String firstName;
private String unionRep;
private String local;
private String deviceToken;
private String unionLegislator;
private String gender;
private String unionCarpenter;

When I call web service I need to call setter for each value. Is there any other way to set whole data in better and efficiant way.

Below is my code to set POJO

 Gson gson = new Gson();

            UserData response = new UserData(jObj);

            String json = gson.toJson(response);

            response = gson.fromJson(json, UserData.class);



            /* Data data1 = ParseManager.parseLoginResponse(result);

            UserManager.setLoginResponse(data1);

           Data d =  UserManager.getUer();*/

           /* Bundle bundle = getIntent().getExtras();
            Data userData = (Data) bundle.getParcelable("email");*/

            //Log.e("email Id is","-----------------"+ userData.getEmail());
            // here to set the parser class and fetch the result

            Data data = new Data();

            data.setId(response.getData().getId());
            data.setFirstName(response.getData().getFirstName());
            data.setLastName(response.getData().getLastName());
            data.setMobile(response.getData().getMobile());
            data.setEmail(response.getData().getEmail());
            data.setZipcode(response.getData().getZipcode());
            data.setGender(response.getData().getGender());
            data.setPassword(response.getData().getPassword());
            data.setUnionCarpenter(response.getData().getUnionCarpenter());
            data.setUnionRep(response.getData().getUnionRep());
            data.setLocal(response.getData().getLocal());
            data.setUnionContractor(response.getData().getUnionContractor());
            data.setUnionLegislator(response.getData().getUnionLegislator());
            data.setUniounSupplier(response.getData().getUniounSupplier());
            data.setNewsfeedCategories(response.getData().getNewsfeedCategories());
            data.setSendNotifications(response.getData().getSendNotifications());
            data.setLastUpdate(response.getData().getLastUpdate());
Community
  • 1
  • 1
Kshitij Vyas
  • 83
  • 1
  • 9

7 Answers7

2

Just create a method in which you can set every values, and pass all values as params to this method.

You need to call only one method.

class YourPOJO {
    String var1, var2;
    int var3;
    .
    .
    .

    public void setData(String var1, String var2, int var3) {
        this.var1 = var1;
        this.var2 = var2;
        this.var3 = var3;
    }
}
Ravi Sisodia
  • 776
  • 1
  • 5
  • 20
2

You can do it with Jackson ObjectMapper

ObjectMapper mapper = new ObjectMapper();
SourceBean source = ...;
TargetBean target = mapper.convertValue(source, TargetBean.class);

For best performance, it is best to do it with getters and setters. However, for code simplicity, you may use jackson

Alternately, If you don't mind using apache library, BeanUtils from Apache Commons will handle this quite easily, using

copyProperties(DestObject, SourceObject).

Rahul
  • 15,979
  • 4
  • 42
  • 63
  • Yes I can understand this code is woking fine with no error and I can use it in app. But I m bit lazy to set the large data. What if I get 30 values from web service. I need to call 30 setters. Thats why looking for more improved way. – Kshitij Vyas Dec 30 '16 at 05:14
  • @KshitijVyas Aren't you looking for something similar to what is specified in the answer? – Rahul Dec 30 '16 at 09:02
  • I implement the other way around. I ll give it a try. I had used JAKSON but found GSON more flexible to use that's why go with that. I ll give it a try for sure..Thnx for guidance. – Kshitij Vyas Dec 30 '16 at 09:16
2

You can create a constructor with parameteres of your POJO and pass all your data in the parameter.

public class DummyPOJO{
private String data1;
private String data2;
.....

public DummyPOJO(String data1, String data2,....){
  this.data1=data1;
  this.data2=data2;
  ......
}   
}

If you are using any IDE like android studio you can directly create a constructor with parameters using ALT+INS

Kuldeep Dubey
  • 1,097
  • 2
  • 11
  • 33
1

use retrofit framwork. so you can easyly manage data.and set it in to adapter or else , some code below.

 public interface RestClient {

 @FormUrlEncoded
 @POST("/order/order_list")
 void order(@Field("token") String token,
              @Field("page") String page,
              Callback<Home> callback);
}

first create inarface like above than create finalwrapper class

public class FinalWrapper<T> {
public final T value;

public FinalWrapper(T value) {
    this.value = value;
}
}

than other file create name with RetrofitClient

 public class RetrofitClient {
private final static String TAG = RetrofitClient.class.getSimpleName();

private static FinalWrapper<RetrofitClient> helperWrapper;
private static final Object LOCK = new Object();
private final RestClient mRestOkClient;


private RetrofitClient() {
    // Rest client without basic authorization
    mRestOkClient = ServiceGenerator.createService(RestClient.class);
}

/**
 * @return
 */
public static RetrofitClient getInstance() {
    FinalWrapper<RetrofitClient> wrapper = helperWrapper;

    if (wrapper == null) {
        synchronized (LOCK) {
            if (helperWrapper == null) {
                helperWrapper = new FinalWrapper<>(new RetrofitClient());
            }
            wrapper = helperWrapper;
        }
    }
    return wrapper.value;
}

public RestClient getRestOkClient() {
    return mRestOkClient;
}

}

and finally create service ganarater

public class ServiceGenerator {
// No need to instantiate this class.
private ServiceGenerator() {
}

/**
 * @param serviceClass
 * @param <S>
 * @return
 */
public static <S> S createService(Class<S> serviceClass) {
    final OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setReadTimeout(Constant.CONNECTION_TIMEOUT, TimeUnit.SECONDS);
    okHttpClient.setConnectTimeout(Constant.CONNECTION_TIMEOUT, TimeUnit.SECONDS);

    RestAdapter.Builder builder = new RestAdapter.Builder()
            .setEndpoint(Constant.BASE_URL)
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .setClient(new OkClient(okHttpClient));

    RestAdapter adapter = builder.build();


    return adapter.create(serviceClass);

}
}

and in your activity where you call service

  public void orderApi() {
    if (Utility.checkInternetConnection(getContext())) {
        if (db == 1) {
            getMessageUtil().showProgressDialog();
        }
        RetrofitClient.getInstance().getRestOkClient().
                order(VPreferences.getAccessToken(getContext()),
                        String.valueOf(page),
                        callback);
    }
}

private final retrofit.Callback callback = new retrofit.Callback() {
    @Override
    public void success(Object object, Response response) {
        getMessageUtil().hideProgressDialog();
        Home home = (Home) object;
        if(home.getResult().equalsIgnoreCase("1")) {
            total = home.getOrders().getLast_page();
            homeOrderses.addAll(home.getOrders().getData());
            tabOrderAdapter = new TabOrderAdapter(getContext(), homeOrderses);
            if (db == 1) {
                rlOrder.setAdapter(tabOrderAdapter);
            } else {
                rlOrder.getAdapter().notifyDataSetChanged();
            }
        }
        else {
            Toast.makeText(getContext(), "First Login", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(getContext(), LoginActivity_.class);
            startActivity(intent);
            getActivity().finish();
        }

    }

    @Override
    public void failure(RetrofitError error) {
        Log.e("ERROR", error + "");
        getMessageUtil().hideProgressDialog();
    }
};

note put retrofit dependancy

Payal Sorathiya
  • 756
  • 1
  • 8
  • 23
1

Create POJO class like this....

public class GetAllStudentModel {
private int id;
private String name;
private String branch;
private ArrayList<GetAllStudentModel> list;
private String sem;
private String photo_url;
private String email;
private String mobile;
private String dob;
public GetAllStudentModel(int id, String name, String branch, String sem, String photo_url,String mobile, String email,String dob) {
    this.id = id;
    this.name = name;
    this.branch = branch;
    this.sem = sem;
    this.photo_url=photo_url;
    this.mobile = mobile;
    this.email = email;
    this.dob=dob;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getBranch() {
    return branch;
}

public void setBranch(String branch) {
    this.branch = branch;
}

public ArrayList<GetAllStudentModel> getList() {
    return list;
}

public void setList(ArrayList<GetAllStudentModel> list) {
    this.list = list;
}

public String getSem() {
    return sem;
}

public void setSem(String sem) {
    this.sem = sem;
}

public String getPhoto_url() {
    return photo_url;
}

public void setPhoto_url(String photo_url) {
    this.photo_url = photo_url;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getMobile() {
    return mobile;
}

public void setMobile(String mobile) {
    this.mobile = mobile;
}

public String getDob() {
    return dob;
}

public void setDob(String dob) {
    this.dob = dob;
}


}

and CALL this cunstructor like that..

 try{
     JSONArray ja = response.getJSONArray(TAG_RESULTS);
     for(int i=0; i < ja.length(); i++){

          JSONObject jsonObject = ja.getJSONObject(i);
          id = Integer.parseInt(jsonObject.getString("id").toString());
          name = jsonObject.getString(TAG_NAME);
          branch = jsonObject.getString(TAG_BRANCH);
          sem = jsonObject.getString("semester");
          photo_url=jsonObject.getString("photo");
          email=jsonObject.getString("email");
          mobile=jsonObject.getString("mobile");
          dob=jsonObject.getString("dob");
          getAllStudentModel = new GetAllStudentModel(id,name,branch,sem,photo_url,email,mobile,dob);
          list.add(getAllStudentModel);
     }
 }catch(JSONException e){e.printStackTrace();}
Abhishek Singh
  • 9,008
  • 5
  • 28
  • 53
1

You can convert the json to Map using Gson like below, quoted from here:-

Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson("{'key1':'value1','key2':'value2'}", type);

You can use Apache Commons BeanUtils to do this in a very clean way.

Populate a POJO from Map, javadoc for below method:-

org.apache.commons.beanutils.BeanUtils.populate(Object bean, Map properties)

Map key should be the property or attribute name in POJO class, internally this method uses Java Reflection API to call the setter methods.

Your code will look like below:-

String json = gson.toJson(response);
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> jsonMap= gson.fromJson(json , type);
Data data = new Data();
BeanUtils.populate(data , jsonMap);
Community
  • 1
  • 1
Amit Bhati
  • 5,569
  • 1
  • 24
  • 45
0

Basically your problem is mapping one POJO to Other POJO.

You can use Dozer mapper for this.

Dozer Example

Check Dozer documentation here.

Siddharth Kumar
  • 86
  • 2
  • 13