DDK
DDK

Reputation: 1038

HashMap to JSONArray and handling the response in jquery

I have this HashMap< String,Employee>() object and I convert it to JSONArray as below

JSONArray jarray = JSONArray.fromObject(myHashMap);

Note that the key in the map is always a numeric literal but its datatype is String.

Below is the code which is used to set json string to the response.

response.setContentType("text/text;charset=utf-8");
response.setHeader("cache-control", "no-cache");
PrintWriter out = response.getWriter();
out.println(jarray.toString());
out.flush();

The json string i get is

[{"1":{"empAge":32,"empEmail":"[email protected]","empId":1,"empName":"myname","empTel":"33445"}]

how to get the value of empName in map with key value 1?

$.ajax({
type: "POST",
url: "/MyApp/TestAction.do",
dataType :"json",
success: function(response){
     alert(response.1[0].empName);// I get java script error in this statement
    },
    error: function(e){
        alert('Error: ' + e);
    }
 });

Upvotes: 1

Views: 4260

Answers (1)

Tomer
Tomer

Reputation: 17930

You are using the wrong header:

 response.setContentType("text/text;charset=utf-8");

Change it to:

response.setContentType("application/json;charset=utf-8");

currently you are getting it as a string so you cannot use it as an object, once you change the header you'll get it as a json object and would be able to use it.

As a side note, "1" is not a very good key, if you can replace it to a more descriptive string, I'd suggest you do that.

Upvotes: 2

Related Questions