java - How to get data through JSON in a particular format -
following code snippet used online roster gtalk
if (status == true) { roster roster =connection.getroster(); collection<rosterentry> entries =roster.getentries(); system.out.println(roster.getentrycount()); int count1 = 0; int count2 = 0; for(rosterentry r:entries) { presence presence = roster.getpresence(r.getuser()); if(presence.gettype() == presence.type.unavailable) { // system.out.println(user + "is offline"); count1++; } else { string rosternamesjson = new gson().tojson(r.getname()); string rosteruserjson =new gson().tojson(r.getuser()); response.setcontenttype("application/json"); response.setcharacterencoding("utf-8"); //array of 2 elements string rosterinfojson=response.getwriter().write("rosternamesjson"+"rosteruserjson"]); response.sendredirect("roster.jsp"); //system.out.println(name+user + "is online"); count2++; } } }
now in jsp page want populate roster name , jid i.e xoxoxo:xoxoxo@gmail.com jjj:jjj@gmail.com , on. how achieve this?
should construct json element i.e
users { name: jid: }
and write function in jsp page access data?
the function have is
$(function() { $.getjson('xxxservlet', function(rosterinfojson) { var $ul = $('<ul>').appendto($('#roster')); $.each(rosterinfojson, function(index, rosterentry) { $('<li>').text(rosterentry.user).appendto($ul); }); }); });
yes. should construct json
users { name: jid: }
you may want define java class mapping json.
public class myuser{ public string name; public string jid; public myuser(string name, string jid){ this.name=name; this.jid=jid; } }
and then, append online uses list or something
arraylist<myuser> mul = new arraylist<myuser>(); if (status == true) { ... ... for(rosterentry r:entries) { if(...){ ... } else { mul.add(new myuser(r.getname(),r.getuser()); count2++; } } response.setcontenttype("application/json"); response.getwriter().write(new gson().tojson(mul)); response.setcharacterencoding("utf-8"); response.sendredirect("roster.jsp");
in javascript
... $('<li>').text(rosterentry.name +":"+rosterentry.jid).appendto($ul); ...
Comments
Post a Comment