I am not very good with Java, so please forgive me for my ignorance. 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.
{
"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.
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);
Contact&Keyclasses with the required member types, then create aList<Contact>with the records retrieved from the DB, and serialize it to JSON format? Alternatively, depending on the library you use, you can create generic JsonObject.JsonObjectdirectly? JsonObject can put("key",Object) like what you need.keyMap.put("value", res.getString("email"));you are replacing the value that was previously registered with the key "value", don't you? This looks like a typical case of not creating your own data structure and instead taking something that is already there, despite the fact that is totally doesn't fit at all.