Arun.K
Arun.K

Reputation: 11

Hashmap of hashmaps converted to json in java. When sent to jsp, i parsed it in javascript. But it is not parsed correct in javascript

In java

HashMap<String, HashMap<String, String>> modFieldHash = new HashMap<String,HashMap<String, String>>();    
JSONObject modFieldJson = new JSONObject(modFieldHash); 
request.setAttribute("hash",modFieldJson);

In jsp,

JSONObject modFieldHash = (JSONObject)request.getAttribute("hash");

In javascript,

var modField = JSON.parse(<%=modFieldHash%>);

is my code. If hashmap is <"chk",<"chk1","chk1">>, then it is received as {"chk","{chk1=chk1}"} in js. JSON.parse wont work on the second hashmap.

Upvotes: 1

Views: 554

Answers (1)

trincot
trincot

Reputation: 350725

For nested hash maps you will get better JSON rendering with the GSON library.

Use it in java as follows:

HashMap<String, HashMap<String, String>> modFieldHash =
    new HashMap<String,HashMap<String, String>>();    
Gson gson = new Gson(); 
request.setAttribute("hash", gson.toJson(modFieldHash));

Upvotes: 1

Related Questions