admin管理员组

文章数量:1289893

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);

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);
Share Improve this question edited May 27, 2011 at 9:42 AabinGunz asked May 27, 2011 at 8:43 AabinGunzAabinGunz 12.3k54 gold badges148 silver badges220 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

I think you should slightly change the JSON that you send form the servlet: {employees:[{fullname:"Abhishek Raj Simon", email:"[email protected]"}]} would work a bit better in that context.

I'd remend jQuery as pap has also advised. The code would be:

$.getJSON('/temp/jsontest', function(data) {
   var items = [];
   for (employee in data.employees) {
       items.push(employee.fullname + '<' + employee.email + '>');
   }
   alert('Employees: ' + items.join(', '));
});

In my opinion it is lot simpler and easier to understand than dealing with raw XHR. The jQuery $.getJSON will do GET for you, and then evaluate the JSON response so the function is presented with nice JSON representation of your data that is easy to manipulate.

EDIT:

After interesting discussion here is some more improvement you could introduce in order to replace the low-level code with proper JQuery-based implementation.

<script>
  $(document).ready(function() {
    $("#json-button").click(function() {
      $.getJSON('/temp/jsontest', function(data) {
        var items = [];
          for (employee in data.employees) {
            items.push(employee.fullname + '<' + employee.email + '>');
          }
          alert('Employees: ' + items.join(', '));
      });
    });
  });
</script>

<form>
    <input id="json-button" type="button" value="get me some json">
</form>

I would suggest you to use GSON library, which enables you to serialize Java object to json, to avoid writing it by yourself. If you do not want to use GSON, there are plenty of others libraries which uses same capabilities.

//inside your get method

Gson gson = new Gson( );
List<Employe> employees = new ArrayList<Employe>( );

// populate your list here

response.setContentType( "application/json");
response.getWriter( ).println( gson.toJson( employees));


//end

then in javascript you can do as it's already suggested in other answers here. And do pay attention to update response content type.

var res=client.responseText;
var temp = 'resObj=' + res;
eval(temp);
alert(resObj.employees.fullname);

JSON is just text, but in javascript syntax. You need to pass it through the "eval" method that will evaluate and execute the text as javascript.

My advice, though, is to use jQuery or some other javascript framework to avoid having to mess with all that boiler-plate javascript.

It's because you are receiving the JSON String but you're not converting it into a JSON Object. There's a eval() function that evaluates your JSON String and returns a JSON Object.

The following example should work (though untested).

if(client.readyState==4&&client.status==200)
     {
        var res=eval('(' + client.responseText; + ')');
        alert(res);     
        alert(res.employees[0].fullname);
        alert(res.employees[0].email);   
     }

WARNING: I suggest reading the security concerns when using eval(). Alternatively, go to JSON and download a Javascript JSON parser or use JQuery instead.

本文标签: javahow to get JSON objects from servletStack Overflow