0

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);
5
  • 2
    Why not create the Contact & Key classes with the required member types, then create a List<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. Commented Mar 8, 2018 at 16:41
  • 1
    Why don't you just put the data into a JsonObject directly? JsonObject can put("key",Object) like what you need. Commented Mar 8, 2018 at 16:41
  • From a quick glance at your code I really don't think Maps are the data structure you should use. You do for example understand that each Key is unique and when you do 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. Commented Mar 8, 2018 at 16:43
  • This smells of object phobia - simple create proper types and populate them. Generally lists of maps of maps of lists in an OO language are a sign that you are doing it wrong... Commented Mar 8, 2018 at 16:44
  • @sakiM The reason for not putting it into JSON object directly is that I will need the list to break down into chunks or partitions. I thought having list would make partitioning of data easy. Commented Mar 9, 2018 at 8:25

3 Answers 3

4

Instead of using generic structures like List or Map, you'd be better off designing classes which model the structure you need. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

I have created the class but still couldn't figure out how to fill it, could you please give me an example of usage?
0

Create a Model Class and use it's getter and setter methods.

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.

Kudos.... Enjoy

Comments

0

If map is your preferred data structure, you can use the code below:

    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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.