【问题标题】:How to map an arraylist of hashmap to anothoer hashmap arraylist如何将hashmap的arraylist映射到另一个hashmap arraylist
【发布时间】:2019-09-13 14:24:59
【问题描述】:

我有一个Switch,其中包含13 个case,每个案例执行不同的sql 请求。我在ArrayList<HashMap<String, String>> 中得到了结果。这个结果应该用 angular 显示,现在我正在使用这个 this.respTest = JSON.stringify(response); 所以它显示了 "key":"value" 的列表。

我的问题是因为每个请求都会给我不同的数据库字段和值,所以我想合并一些字段。 我创建了这个类:

public class DataCollect {

private String type ; 
private String entity ; 
private String modPar ;
private String dateModif ; 
private String numVersion ;

public DataCollect(String type, String entity, String modPar, String dateModif, String numVersion) {

    this.type = type;
    this.entity = entity;
    this.modPar = modPar;
    this.dateModif = dateModif;
    this.numVersion = numVersion;
}

public DataCollect() {

}
public String getType() {
    return type;
}
public void setType(String type) {
    this.type = type;
}
public String getEntity() {
    return entity;
}
public void setEntity(String entity) {
    this.entity = entity;
}
public String getModPar() {
    return modPar;
}
public void setModPar(String modPar) {
    this.modPar = modPar;
}
public String getDateModif() {
    return dateModif;
}
public void setDateModif(String dateModif) {
    this.dateModif = dateModif;
}
public String getNumVersion() {
    return numVersion;
}
public void setNumVersion(String numVersion) {
    this.numVersion = numVersion;
} }

在这个类中,我应该将字段的名称影响到我创建的变量,并作为返回一个带有我从数据库中提取的数据的 hashmap 的数组列表。 我的意思是我曾经返回例如 "field-name":"value" ,我想返回 "type":"value","entity":"value" ..etc

我在后端使用 springboot,在前端使用 angular 5。 任何帮助将不胜感激。

【问题讨论】:

  • 是您将 SQL 查询 [resultSet] 的结果转换为 List ...?? 的问题
  • @ShubhamMaheshwari 不,它更复杂,我已经在数组列表中得到了结果,但我不想制作一个特定/个性化的列表,而不是将结果显示为“字段- name":"value" ,我将其显示为我已经创建的变量之一,例如 "type":"value"

标签: java spring-boot arraylist hashmap


【解决方案1】:

您本质上想要的是一种将 [每个] 哈希图中的键映射到“DataCollect”POJO 中相应成员变量的方法。

如果存在的键和对应的成员变量之间存在一对一的映射,您可以在“DataCollect”中公开一个公共构造函数,该构造函数接受哈希映射并构造相应的对象。

public DataCollect(Map<String, String> result) {
    this.type = result.get("type");
    this.entity = result.get("db_entity_key");
    ...
}

如果没有一对一的映射,您必须创建一个工厂类,它将您的 Map 作为输入和一些上下文,并返回构造的 DataCollect 对象。

一旦你有了构造函数或工厂类,你只需要遍历你的结果列表,并把每个 Map 转换成 DataCollect 对象。

您的控制器应该自动将 DataCollect 对象序列化为相应的 JSON,或者您甚至可以使用 Jackson 的 ObjectMapper 来实现相同的目的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 2014-08-04
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    相关资源
    最近更新 更多