假设我有这样的 Json 响应:
{
"status": true,
"data": {
"29": "Hardik sheth",
"30": "Kavit Gosvami"
}
}
我正在使用 Retrofit 来解析 Json 响应。根据 this回答我将不得不使用
Map<String, String>
这将提供 map 中的所有数据。现在我想要的是ArrayList<PojoObject>
.PojoObject.class
public class PojoObject {
private String mapKey, mapValue;
public String getMapKey() {
return mapKey;
}
public void setMapKey(String mapKey) {
this.mapKey = mapKey;
}
public String getMapValue() {
return mapValue;
}
public void setMapValue(String mapValue) {
this.mapValue = mapValue;
}
}
转换
Map<key,value>
的最佳方法是什么?到 List<PojoObject>
?
最佳答案
如果您可以扩展您的类以使构造函数也采用这些值:
map.entrySet()
.stream()
.map(e -> new PojoObject(e.getKey(), e.getValue()))
.collect(Collectors.toList());
如果你不能:
map.entrySet()
.stream()
.map(e -> {
PojoObject po = new PojoObject();
po.setMapKey(e.getKey());
po.setMapValue(e.getValue());
return po;
}).collect(Collectors.toList());
请注意,这使用 Java 8
Stream
API。
关于java - 如何将 map 转换为对象数组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42694964/