How do I create a multidimensional HashMap or Hashtable in JSP / Java and convert it to a JSON object?

10,599

Solution 1

In JSON, the {} is mappable as Java Map and the [] is mappable as Java List.

So, to achieve the following JSON format,

{
  "results": [ {
    "address_components": [ {
      "long_name": "1600",
      "short_name": "1600"
    }, {
      "long_name": "Amphitheatre Pkwy",
      "short_name": "Amphitheatre Pkwy"
    }, {
      "long_name": "Mountain View",
      "short_name": "Mountain View"
    }, {
      "long_name": "California",
      "short_name": "CA"
    }, {
      "long_name": "United States",
      "short_name": "US"
    }, {
      "long_name": "94043",
      "short_name": "94043"
    } ]
  } ]
}

you need a (deep breathe) Map<String, List<Map<String, List<Map<String, String>>>>>.

List<Map<String, String>> addressComponents = new ArrayList<Map<String, String>>();
Map<String, String> addressComponent1 = new HashMap<String, String>();
addressComponent1.put("long_name", "1600");
addressComponent1.put("short_name", "1600");
addressComponents.add(addressComponent1);
Map<String, String> addressComponent2 = new HashMap<String, String>();
addressComponent2.put("long_name", "Amphitheatre Pkwy");
addressComponent2.put("short_name", "Amphitheatre Pkwy");
addressComponents.add(addressComponent2);
// ...

List<Map<String, List<Map<String, String>>>> results = new ArrayList<Map<String, List<Map<String, String>>>>();
Map<String, List<Map<String, String>>> result1 = new HashMap<String, List<Map<String,String>>>();
result1.put("address_components", addressComponents);
results.add(result1);
// ...

Map<String, List<Map<String, List<Map<String, String>>>>> god = new HashMap<String, List<Map<String,List<Map<String,String>>>>>();
god.put("results", results);
String json = new Gson().toJson(god);
System.out.println(json); // There!

Better is to just use fullworthy Javabeans instead of Map<String, String>.

Solution 2

The line

results_hash.put("results",arr[i]);

will overwrite the last entry with the same key in your Hashtable. Your just replacing the entry with the key "results", not adding to it.

Try something like (pseudocode):

Map<String,String> entry;
Map<String, Map> results = new HashMap<String, Map>();
Map<String,List<Map> address_components = new HashMap<String, List<Map>>();
List<Map> entries = new ArrayList<Map>();

for 1..10 {
   entry = new HashMap<String,String>();
   entry.put("long_name", xxx);
   entry.put("short_name", xxx);
}

address_components.put("address_components", entries);
result.put("result", address_components);

Haven't tested it, but I hope you get the idea... you need to get the inital data structure right.

Solution 3

try this

for (int i=0; i < 10; i++)
{
   numbers.put("Number",i);
   numbers.put("Numberx2",i*2);
   arr[i] = new Hashtable();
   arr[i].put("Comp",numbers);
}
results_hash.put("results",arr);
Share:
10,599
user717236
Author by

user717236

Updated on June 05, 2022

Comments

  • user717236
    user717236 almost 2 years

    I need help creating a multidimensional HashMap or Hashtable in JSP. Why I do I need HashMap or HashTable? Because I ultimately want to pass back to the client a JSON object. If there is another way to ultimately arrive at a JSON object, I'm all ears.

    I also wanted to mention that this thread has been invaluable and I've been expanding on it:

    How can I write a multidimensional JSON object in JSP and pass the JSON object back to JavaScript?

    Here is what I want the result to looks like:

    {
      "results": [ {
        "address_components": [ {
          "long_name": "1600",
          "short_name": "1600"
        }, {
          "long_name": "Amphitheatre Pkwy",
          "short_name": "Amphitheatre Pkwy"
        }, {
          "long_name": "Mountain View",
          "short_name": "Mountain View"
        }, {
          "long_name": "California",
          "short_name": "CA"
        }, {
          "long_name": "United States",
          "short_name": "US"
        }, {
          "long_name": "94043",
          "short_name": "94043"
        } ]
      } ]
    }
    

    Here is my JSP code, which uses a trivial example, instead of real-world data like above:

    Hashtable results_hash = new Hashtable();   
    Hashtable numbers = new Hashtable();
    Hashtable[] arr = new Hashtable[10];
    
    for (int i=0; i < 10; i++)
    {
      numbers.put("Number",i);
      numbers.put("Numberx2",i*2);
      arr[i] = new Hashtable();
      arr[i].put("Comp",numbers);
      results_hash.put("results",arr[i]);
    }
    
    com.google.gson.Gson gson = new com.google.gson.Gson();
    String json = gson.toJson(results_hash);
    out.print(json);
    

    But the JSON object looks like this:

    {
      "results": {
        "Comp":    {
          "Numberx2":18,
          "Number":9 
        }
      }
    }
    

    This is not the desired result. It's only taking the last result and converting it to JSON. So, the problem starts with the multidimensional hash not being built correctly. I'm not sure what is the problem, though. I would appreciate some help. Thank you.

  • user717236
    user717236 almost 13 years
    This worked great, except that the last result is stored 10 times (i.e Number=9, Numberx2=18) in the JSON object. Thank you, though. I don't understand why your solution doesn't produce the desired result, though. I will take a look at the other solutions, as well.
  • user717236
    user717236 almost 13 years
    I modified your example a bit and received the desired result for the exercise. So, thank you again. Code: Hashtable results_hash = new Hashtable(); Hashtable numbers[] = new Hashtable[10]; Hashtable[] arr = new Hashtable[10]; for (int i=0; i < 10; i++) { numbers[i] = new Hashtable(); numbers[i].put("Number",i); numbers[i].put("Numberx2",i*2); arr[i] = new Hashtable(); arr[i].put("Comp",numbers[i]); } results_hash.put("results",arr);
  • user717236
    user717236 almost 13 years
    Excellent, thank you! Does this work for N number of results from, say, a SQL lookup? Or, must you write out each addressComponent (i.e. addresscomponent1, addressComponent2,..., addressComponentN)? What is the difference between Map and HashMap/HashTable? Thank you.
  • BalusC
    BalusC almost 13 years
    Just do it in a loop. Map is an interface. HashMap is an implementation. Hashtable is the legacy predecesor of HashMap which was succeeded over a decade ago (read up to date tutorials/books please). download.oracle.com/javase/tutorial/collections/interfaces/…
  • user717236
    user717236 almost 13 years
    Question for all: Is it possible to dynamically resize HashTable/HashMap, Map structures? Does Java have built-in functionality to dynamically resize hashes? I've been investigating and, so far, I haven't found an answer, other than Linked Lists. Thank you.
  • BalusC
    BalusC almost 13 years
    Map and List ARE dynamically resizable. Just call add() or put() to add new items, exactly as in my answer. Click the tutorial link in my previous comment to learn more about it.
  • user717236
    user717236 almost 13 years
    Thank you for your knowledge and advice. I will take a look at the link and study it. I appreciate your help.