isahilarora isahilarora - 5 months ago 15
Java Question

Issue with conversion of Map inside a Map into JSON in Java

I have a treemap in Java which has structure like this below:

public static Map<String, Map<String, Integer>> testMap = new TreeMap<String, Map<String, Integer>>();

public String getTestMapInJson(Map<String, Map<String, Integer>> testMap){
ObjectMapper mapper = new ObjectMapper();
String testMapInJson = mapper.writeValueAsString(testMap);
return testMapInJson;
}


Now, when I am trying to convert this map in JSON using Jackson API(snippet above), I am getting data like this and I want to populate this data in HTML tables.

[
{
"key": "1.1.1.1",
"value": {
"string1": 500,
"string2": 400
}
},
{
"key": "2.2.2.2",
"value": {
"string1": 500,
"string2": 400
}
}
]


HTML table output is like:

IP Address Value
1.1.1.1 [object Object]
2.2.2.2 [object Object]


I want it like this:

IP Address Value
1.1.1.1 String1 count1
String2 count2
2.2.2.2 String1 count1
String2 count2


The internal hashmap doesn't get converted exactly into JSON format. I want something so that the internal hashmap too gets converted into similar map like the outer map.
It's feasible for me to make changes on any side (client/server). What should I do?

Answer
var resp = [
{
    "ip": "1.1.1.1",
    "data": {
        "string1": 500,
        "string2": 400
    }
},
{
    "ip": "2.2.2.2",
    "data": {
        "string1": 500,
        "string2": 400
    }
}
]

To access the Object:

for(var obj : resp) {
     $.each(obj, function(key,value){
         alert(key + "==" + value);
         if(key == "data") {
            $.each(value, function(innerKey, innerVal) {
               alert(innerKey + "===" + innerVal);
            });
         }
     });
}

To design table:

var table = $("<table>");
//header
var header = $("<tr>").append($("<th>").text("IP Address")).append($("<th>").text("Value"));

for(var obj : resp) {
    $.each(obj, function(key,value){
        var isFirst = true;
        if(key == "data") {
            $.each(value, function(innerKey, innerVal) {
              var tr;
              if(isFirst) {
                  // ip address and value
                  tr = $("<tr>").append($("<td>").text(value)).append($("<td>").text(innerKey + " " + innerValue));
                  isFirst = false;
              } else {
                  // blank and value
                  tr = $("<tr>").append($("<td>").text("")).append($("<td>").text(innerKey + " " + innerValue));
              }
              table.append(tr);
            });
         }
    });
}