I am making a simple html servlet program where I need get JSON object from the servlet, and in html I am able to get the data, but how can i refer to each attribute?
Here is the servlet get method
PrintWriter out=response.getWriter();
StringBuffer emps = new StringBuffer("{employees:[");
emps.append("{fullname:\"Abhishek Raj Simon\"},{email:\"[email protected]\"}]");
emps.append("}");
out.println(emps);
JS to send
function getJson()
{
var url_action="/temp/jsontest";
var form=document.forms["mainForm"];
var splitOutput;
var client;
var dataString;
if (window.XMLHttpRequest){
client=new XMLHttpRequest();
} else {
client=new ActiveXObject("Microsoft.XMLHTTP");
}
client.onreadystatechange=function(){
if(client.readyState==4&&client.status==200)
{
var res=client.responseText;
alert(res);
alert(client.responseText.employees.fullname); //DOES NOT WORK
alert(client.responseText.employees.email); //DOES NOT WORK
}
};
client.open("GET",url_action,true);
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.send();
and a simple form
<form>
<input type="button" value="get me some json" onclick="getJson();">
</form>
When i click on the button, i get only 1 alert displaying {employees:[{fullname:"Abhishek Raj Simon"},{email:"[email protected]"}]} How can i fetch Abhishek Raj Simon and [email protected] using fullname and email respectively?
Edited after reading post from Artem
my servlet
Gson gson = new Gson( );
List<Employee> employees = new ArrayList<Employee>();
Employee emp=new Employee();
emp.setFullname("Abhishek Raj Simon");
emp.setEmail("[email protected]");
employees.add(emp);
response.setContentType( "application/json");
out.println( gson.toJson( employees));
js part
var res=eval('(' + client.responseText + ')');
alert(res);
alert(res.employees.fullname);
alert(res.employees.email);