• Servlet 返回Json数据格式


    其实就是把数据库中的数据查询出来拼接成一个Json数据

     1 import dao.UserDao;
     2 import endy.User;
     3 
     4 import javax.servlet.ServletException;
     5 import javax.servlet.annotation.WebServlet;
     6 import javax.servlet.http.HttpServlet;
     7 import javax.servlet.http.HttpServletRequest;
     8 import javax.servlet.http.HttpServletResponse;
     9 import java.io.IOException;
    10 import java.io.PrintWriter;
    11 import java.util.List;
    12 
    13 @WebServlet("/Json")
    14 public class Json extends HttpServlet {
    15     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    16 
    17     }
    18 
    19     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    20         UserDao ud=new UserDao();
    21         List<User> users=ud.FandAll();
    22         response.setCharacterEncoding("utf-8");
    23         response.setContentType("application/json;charset=utf-8");
    24         PrintWriter out=response.getWriter();
    25         String[] keys={"id","name","pwd","phone","img"};//属性名称
    26         StringBuffer json=new StringBuffer("[");
    27         for (int i=0;i<users.size();i++){
    28             json.append("{");
    29             User u=users.get(i);
    30             Object[] values=u.toarry();
    31             for (int j=0;j<keys.length;j++){
    32                 json.append("""+keys[j]+"":""+values[j]+""");
    33                 if (j<keys.length-1) json.append(",");
    34             }
    35             json.append("}");
    36             if (i<users.size()-1) json.append(",");
    37         }
    38         json.append("]");
    39         out.write(json.toString());
    40         out.close();
    41     }
    42 }

     这里是后台直接拼成json字符串

    26         StringBuffer json=new StringBuffer("[");
    27         for (int i=0;i<users.size();i++){
    28             json.append("{");
    29             User u=users.get(i);
    30             Object[] values=u.toarry();
    31             for (int j=0;j<keys.length;j++){
    32                 json.append("""+keys[j]+"":""+values[j]+""");
    33                 if (j<keys.length-1) json.append(",");
    34             }
    35             json.append("}");
    36             if (i<users.size()-1) json.append(",");
    37         }
    38         json.append("]");
  • 相关阅读:

    第一次发贴,也是在看了首页吵架贴后有感,也给博客园提个提议
    【把玩信息图之标签云】看看我一年的邮件在扯什么
    VS发布Web时自动调用YUICompressor批量压缩JS、CSS
    用JavaScript实现自己的DOM选择器
    一键发布应用了seajs的asp.net项目
    在JavaScript中应用单例模式
    Qt 资料大全
    C#的不足(1):匿名类型的不足之处
    LINQ解析:LINQ to Objects简介
  • 原文地址:https://www.cnblogs.com/feipengting/p/7606992.html
Copyright © 2020-2023  润新知