2011-05-11 46 views
1

繼獲得的數據是代碼片段,用來從GTALK如何通過JSON特定格式

     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++; 
    } 
      } 
} 

獲得在線花名冊現在,在我的jsp頁面我想填充名冊的名字和他jid ie xoxoxo:[email protected] jjj:[email protected]等。我如何實現這一目標?

我要建設的Json元素即

users 
{ 
    name: 
    jid: 
    } 

,然後寫在我的JSP頁面的功能來訪問數據?

我所擁有的功能是

 $(function() { 
     $.getJSON('xxxServlet', function(rosterInfoJson) { 
      var $ul = $('<ul>').appendTo($('#roster')); 
      $.each(rosterInfoJson, function(index, rosterEntry) { 
       $('<li>').text(rosterEntry.user).appendTo($ul); 
      }); 
     }); 
    }); 

回答

2

肯定。您應該構建您的JSON爲

users 
    { 
    name: 
    jid: 
    } 

您可能想要定義映射JSON的Java類。

public class MyUser{ 
    public String name; 
    public String jid; 
    public MyUser(String name, String jid){ 
    this.name=name; 
    this.jid=jid; 
    } 
} 

然後,只是追加所有在線使用的列表或東西

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

在JavaScript

... 
$('<li>').text(rosterEntry.name +":"+rosterEntry.jid).appendTo($ul); 
... 
+0

@ Nishanth,爲什麼我需要一個Java類??我我無法理解映射.. – enthusiastic 2011-05-11 05:10:11

+0

@xoxoxo好,'新的Gson()。toJson(「某些字符串」)'給出''一些字符串「'。您需要打包爲Java對象,因爲您想創建一個與其完全相同的JSON對象。如果你不想使用Object,你也可以使用HashMap。 'HashMap hm = new HashMap (); hm.put(「name」,r.getName()); hm.put(「jid」,r.getUser()); mul.add(hm);'這會做同樣的事情。 – Nishant 2011-05-11 05:22:37