Question

How can I parse a hashmap containing a (String, Object) of json nodes in .jsp per spring mvc?

Controller:

 Map<String, Object> foo = new HashMap<String, Object>(); 
 o o o
 // foo stores json node within the map 
 System.out.println( ( (JsonNode) foo.get("theKey")).toString() );  // Ouput-> "[100]"
 System.out.println( ( (JsonNode) foo.get("theKey")).path(0).getIntValue() ); //Output-> "100"      

 //add to view model tag
 model.addAttribute("foo", foo);

.jsp

<h1>${foo.get("theKey").path(0).getIntValue()}</h1>  // <- Returns 0!   Why?

EDIT: These all work

<h1>${foo["theKey"].path(0).getIntValue()}</h1>  // OK! Returns 100.
<h1>${foo["theKey"].toString()}</h1>  // NO ERROR and returns "[100]"
<h1>${foo["theKey"].path(0).toString()}</h1> // OK! Returns 100.

============================

To add more context...I build the map from the following json:

// rootNode contains all the json below...iterates and assigns to map.
for (JsonNode node : rootNode) {
    foo.put(node.path("key").getTextValue(), node.path("values"));
}

json

[
   {
      "key":"theKey",
      "values":[
         100 
      ]
   }
]
Was it helpful?

Solution

Accessing the map correctly helps...jsonobject methods path() getIntValue() resolve fine.

<h1>${foo["theKey"].path(0).getIntValue()}</h1> // <- THIS WORKS..returns 100!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top