如何以特定格式通过JSON获取数据

时间:2011-05-11 04:31:38

标签: java json servlets jquery gson

以下是用于从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++;
    }
          }
}

现在在我的jsp页面中,我想填充名单和他的jid,即xoxoxo:xoxoxo@gmail.com jjj:jjj@gmail.com等。我如何实现这一目标?

我应该构建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);
            });
        });
    });

1 个答案:

答案 0 :(得分: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);
...