Loading ...
Sorry, an error occurred while loading the content.

Re: [json] How to acess Java Objects, using JSON

Expand Messages
  • krishnappan
    Thanks Josh, it works!!!!!. ... JSON doesn t know how to serialize your Employee object into JSON. You ll want to do something like: List emps = new
    Message 1 of 4 , Oct 22 5:50 PM
      Thanks Josh, it works!!!!!.

      Josh Sled <jsled@...> wrote: On Sun, 2006-10-22 at 19:39 +0000, krish777 wrote:
      > I have a button and onclick of the button, I am calling a servlet and
      > I want to pass Person Object to the client. In doGet() method I am
      > doing the following things
      > JSONObject obj = new JSONObject();
      > Vector v = new Vector();
      > v.add(new Employee("Jim", "1"));
      > v.add( new Employee("Tom", "2"));
      > obj.put("emp", v);
      > res.getWriter().print(obj);
      > In Call back javascript, how to access the properties of the employee
      > object?
      > var jsonExpression = "(" + object.responseText + ")";
      > var customer = eval(jsonExpression);
      > alert(customer.emp[0].firstName);
      > I want to display back employee name and employee id.

      JSON doesn't know how to serialize your Employee object into JSON.
      You'll want to do something like:

      List emps = new ArrayList();
      JSONObject jsonEmp = new JSONObject();
      jsonEmp.put("firstName", employee1.getFirstName());
      jsonEmp.put("id", employee1.getId());
      // any other fields you want...
      // Same for employee2...
      JSONObject toReturn = new JSONObject();
      toReturn.add("employees", emps);
      // serialize into json however...

      Of course, the next step would be to move this into some JsonSerializer
      class ... or maybe classes can implement a "Jsonable" interface that
      lets them move themselves to/from json.

      Also/alternatively, you might want to write a simple reflection-based
      util that can take an object and "json-ify" its fields. You'll probably
      want it to Do The Right Thing for objects assignable to List and Map,
      and keep track of which objects it has already serialized so it doesn't
      loop indefinitely. Also, I recommend having it limit its
      graph-traversal to objects within a particular (set of) packages ...
      like the ones from your project's package namespace. At least, I've
      found something like that useful, even just unidirectionally ... e.g.

      http://asynchronous.org/ - `a=jsled; b=asynchronous.org; echo ${a}@${b}`

      [Non-text portions of this message have been removed]

      Yahoo! Groups Links

      Get your email and more, right on the new Yahoo.com

      [Non-text portions of this message have been removed]
    Your message has been successfully submitted and would be delivered to recipients shortly.