简体   繁体   English

如何在Java中制作具有不同数据类型的地图列表?

[英]How to make a list of maps with different datatypes in java?

I am not very good with Java, so please forgive me for my ignorance. 我对Java不太满意,请原谅我的无知。 I am selecting from a table and looping through the result set to make a list that i can use to convert into json which should look like the following example. 我正在从一个表中选择并遍历结果集以创建一个列表,我可以使用该列表将其转换为json,其外观应类似于以下示例。

{
    "ContactId": "123",
    "key": {
        "type": "email",
        "email": "emailAdress"
    },
    "address": "String",
    "source": "String",
    "revoked": true,
    "text": "String"
}

I don't know how to put them into a list as there are different datatypes i need to put into hash maps. 我不知道如何将它们放入列表,因为我需要将不同的数据类型放入哈希图。 Please note, in the exmaple above key is an object and i am trying to achieve the same thing in the list. 请注意,在上例中,键是一个对象,我正在尝试实现列表中的同一件事。 The ultimate goal is to covert the generated list into json. 最终目标是将生成的列表隐藏到json中。

I have created a few hashmaps but i don't think i am doing it the right way. 我创建了一些哈希图,但是我认为我做的方式不正确。

String Table = "TableName";
String sql = String.format("SELECT id_user, email FROM %s ", Table);
ResultSet res = dbConn.prepareStatement(sql).executeQuery();

Map<String, Map> keyObject = new HashMap<String, Map>();
Map<String, String> keyMap = new HashMap<String, String>();
Map<String, String> mainMap = new HashMap<String, String>();

List<Map<String, String>> contacts = new ArrayList<>();

int i = 0;
while(res.next()){
    keyMap.put("type", "email");
    keyMap.put("value", res.getString("email"));
    keyObject.put("key",  keyMap);
    mainMap.put("tenant", res.getString("id_user"));
    mainMap.put("purpose",  "Marketing sendouts");
    mainMap.put("legalBase",  "Withdrawn");
    contacts.add(i, map);
    i++;
}
System.out.println(contacts);

Instead of using generic structures like List or Map , you'd be better off designing classes which model the structure you need. 与其使用ListMap类的通用结构,不如设计类来对所需的结构进行建模,这样更好。 For instance, in the case above you'll probably have something like: 例如,在上述情况下,您可能会遇到类似以下情况:

public class Contact {
    private int contactId;
    private ContactKey key;
    private String address;
    private String source;
    private boolean revoked;
    private String text;
    // ....
}

Now this is a strongly typed structure which can be easily filled from the resultset. 现在,这是一个强类型结构,可以从结果集中轻松填充它。 A tool like Jackson (or many others) can easily render it as JSON. 像Jackson(或其他许多工具)这样的工具可以轻松地将其呈现为JSON。

If map is your preferred data structure, you can use the code below: 如果map是您的首选数据结构,则可以使用以下代码:

    Map<String, Object> map = new HashMap<>();
    map.put("ContactId", 123);

    Map<String, Object> keyMap = new HashMap<>();
    keyMap.put("type", "email");
    keyMap.put("email", "emailAdress");
    map.put("key", keyMap);

    map.put("address", "aaaa");

    ObjectMapper objectMapper = new ObjectMapper();
    try {
        String json = objectMapper.writer().withDefaultPrettyPrinter().writeValueAsString(map);
        System.out.println(json);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }

I am assuming Jackson is the library you use for serialization. 我假设Jackson是您用于序列化的库。

Create a Model Class and use it's getter and setter methods. 创建一个Model类,并使用它的getter和setter方法。

Eg. 例如。

public class Model {

    private String id;

    private String name;

//Use constructor 
    public Model(String id, String name) { 

        this.id = id;

        this.name = name;

    }


    public String getId() {

        return id;

    }


    public void setId(String id) {

        this.id = id;

    }


    public String getName() {

        return name;

    }


    public void setName(String name) {

        this.name = name;

    }

}


// Now make your Map data Structure center code hereustom .

Hashmap<String,Model> Map = new Hashmap();

// Create a object of your custom Model datastructure and add data.
Model model = new Model("145","Jason");
Map.put("1st",model);

Note that all the data is store at "1st" key of Map. 请注意,所有数据都存储在Map的“第一”键上。

Kudos.... Enjoy 荣誉....享受

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM