2 回答
TA贡献1815条经验 获得超10个赞
List<DTO> dtoList = getDTOList(); // returns list of DTO object
Map<String,Map<String,String> mapCollection
= getMapCollection(); // return String, Map<String,String> pairs
List<Map<String,String>> result = new HashMap<>();
// iterate over dto list
for(DTO singleDTO : dtoList) {
Map<String,String> singleResult = new HashMap<>();
// Add all fields in map
singleResult.put("id",singleDTO.getId());
singleResult.put("name",singleDTO.getName());
singleResult.put("desc",singleDTO.getDesc());
// fetch single map by id lookup
Map<String,Strig> singleMap = mapCollection.get(singleDTO.getId());
// fetch all entries from map
Set<Map.Entry<String,String>> entrySet = singleMap.entrySet();
// add them in hashmap
for(Map.Entry<String,String> singleEntry : entrySet) {
singleResult.put(singleEntry.getKey(),singleEntry.getValue());
Add map in the list
result.add(singleEntry);
}}
//result
[
{
"id":"1", "name":"abc", "desc":"some desc abc", "ID":"1", "mapField1":"field1 value", "mapField2":"field1 value"
},
{
"id":"1", "name":"xyz", "desc":"some desc xyz", "ID":"1", "mapField1":"field1 value", "mapField2":"field1 value"
},
{
"id":"2", "name":"pqr", "desc":"some desc pqr", "ID":"2", "mapField1":"field1 value 2", "mapField2":"field1 value2"
}
]
TA贡献1856条经验 获得超17个赞
假设
假设您的初始对象的类型Item如下所述。
class Item {
String fieldA,fieldB,fieldC;
// Getters / Setter
}
假设您的初始列表Item被称为items
假设您的初始地图被调用map并且是类型Map<String, Map<String,String>>
解决方案
向 Item 类添加一个方法以返回Map<String, String>对象的表示
public Map<String, String> toMap() {
return new HashMap<String, String>() {{
put("fieldA", fieldA);
put("fieldB", fieldB);
put("fieldC", fieldC);
}};
}
创建一个方法来获取fieldD给定fieldA值的值
private String getFieldDValueForFieldAValue(String fieldAValue) {
return map.get(fieldAValue).get("fieldD");
}
创建一种方法以将正确的fieldD值添加到项映射
private Map<String, String> addFieldD(Map<String, String> itemMap) {
itemMap.put("fieldD", getFieldDValueForFieldAValue(itemMap.get("fieldA")));
return itemMap;
}
fieldD然后您可以为每个具有正确值的对象生成一个映射列表
List<Map<String, String>> list = items.stream()
.map(Item::toMap) // Converts all Items to Maps
.map(m -> addFieldD(m)) // Adds the correct fieldD value to each Map
.collect(Collectors.toList()); // make it a List
最后用它制作一个 JSON 字符串:
Type listType = new TypeToken<List<Map<String, String>>>() {}.getType();
Gson gson = new Gson();
String json = gson.toJson(list, listType);
System.out.println(json);
这将输出以下 JSON:
[
{"fieldA":"lookupval1","fieldC":"val3","fieldB":"val2","fieldD":"xxx"},
{"fieldA":"lookupval1","fieldC":"val6","fieldB":"val5","fieldD":"xxx"},
{"fieldA":"lookupval2","fieldC":"val9","fieldB":"val8","fieldD":"yyy"}
]
添加回答
举报