json数据构造

强颜欢笑 提交于 2019-12-10 22:19:45

public class JsonServerlet extends HttpServlet{

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();

        //1.普通生成json数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("key","value");
        out.println(jsonObject);

        out.println("</br>");

        //2.通过list生成json数据
        List list = new ArrayList();
        list.add("first");
        list.add("second");
        list.add("third");
        JSONArray jsonArray = JSONArray.fromObject(list);
        out.println(jsonArray);

        out.println("</br>");

        //3.通过map生成json数据
        Map map = new HashMap();
        map.put("key1","value1");
        map.put("key2","value2");
        map.put("key3","value3");
        JSONObject jsonObject3 = JSONObject.fromObject(map);
        out.println(jsonObject3);
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!