将常量和对应的value整合为map,不想代码写得难看,一堆的for equal?
for (entity e : list) {
// 体积
if("vol".equals(e.getCode())) {
result.setVolume(e.getValue());
continue;
}
// 重量
if("weight".equals(e.code())) {
resultVo.setWeight(e.getValue());
continue;
}
// 数量
if("num".equals(e.code())) {
resultVo.setNum(e.getValue());
continue;
}
}
何不试试list转map,用Gson序列化map? 重点jdk8的list转map和Gson的@SerializedName
// 将list转为(code,value)键值对
Map<String, Object> map = list.stream().collect(Collectors.toMap(entity::getCode, entity::getValue));
// Gson序列化,将常量指定为类Bean里各属性@SerializedName的值
Bean result = gson.fromJson(gson.toJson(map),new TypeToken<Bean>() {}.getType());
Bean实体如下:
public class Bean {
@SerializedName("vol")
private Integer volume;
@SerializedName("weight")
private Integer weight;
@SerializedName("num")
private Integer num;
public Integer getVolume() {
return volume;
}
public void setVolume(Integer volume) {
this.volume = volume;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
}
@SerializedName的功能和原理:
源码在com.google.gson.internal.bind.ReflectiveTypeAdapterFactory的方法getFieldNames,使用在
getBoundFields()里