您好我正在寻找不逐一设置POJO类的所有值的方法。必须一次性调用setter。
我有这个POJO数据。
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;
当我调用Web服务时,我需要为每个值调用setter。有没有其他方法可以更好,更有效地设置整个数据。
以下是我设置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());
答案 0 :(得分:2)
只需创建一个方法,您可以在其中设置每个值,并将所有值作为参数传递给此方法。
您只需要调用一种方法。
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;
}
}
答案 1 :(得分:2)
您可以使用Jackson ObjectMapper
ObjectMapper mapper = new ObjectMapper();
SourceBean source = ...;
TargetBean target = mapper.convertValue(source, TargetBean.class);
为了获得最佳性能,最好使用getter和setter。但是,为了简化代码,您可以使用jackson
或者,如果你不介意使用apache库,那么来自Apache Commons的BeanUtils将很容易处理,使用
copyProperties(DestObject, SourceObject)
。
答案 2 :(得分:1)
您可以使用POJO的参数创建构造函数,并将所有数据传递给参数。
public class DummyPOJO{
private String data1;
private String data2;
.....
public DummyPOJO(String data1, String data2,....){
this.data1=data1;
this.data2=data2;
......
}
}
如果你使用像android studio这样的任何IDE,你可以使用ALT+INS
答案 3 :(得分:1)
使用改造框架。 所以你可以轻松管理数据。并将其设置为适配器或者下面的一些代码。
public interface RestClient {
@FormUrlEncoded
@POST("/order/order_list")
void order(@Field("token") String token,
@Field("page") String page,
Callback<Home> callback);
}
首先创建如上所述的inarface而不是创建finalwrapper类
public class FinalWrapper<T> {
public final T value;
public FinalWrapper(T value) {
this.value = value;
}
}
比使用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;
}
}
最后创建服务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);
}
}
并在您调用服务
的活动中 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();
}
};
注意改装依赖
答案 4 :(得分:1)
像这样创建POJO类......
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;
}
}
并且像这样调用这个cunstructor ..
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();}
答案 5 :(得分:1)
您可以使用Gson将json转换为Map,如下所示 here: -
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson("{'key1':'value1','key2':'value2'}", type);
您可以使用Apache Commons BeanUtils以非常干净的方式执行此操作。
从地图填充POJO javadoc以获取以下方法: -
org.apache.commons.beanutils.BeanUtils.populate(Object bean, Map properties)
Map键应该是POJO类中的属性或属性名称,在内部,此方法使用Java Reflection API来调用setter方法。
您的代码如下所示: -
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);
答案 6 :(得分:0)