javaEE必知必会第五讲jsonlib
- 5.1 下载jsonlib所需的6个jar包
- 5.2 JSON转换成Object的案例
5.1 下载jsonlib所需的6个jar包
点此进入下载官网
这个网址是maven仓库的国内镜像地址,比较好用
选择合适的版本
一般选择jar依赖包方式下载
下载完成后即可,同理,在这个网站里继续下载另外5个json包
如果最后一个json-lib下载不了,你可以尝试用镜像文件,你也可以到另一个网站中去下载json-lib下载网址,点此进入
然后复制到相应的目录下,如下图
5.2 JSON转换成Object的案例
新建一个servlet, GetJSONAarrayData代码如下
package com.iflytek.servlet;import java.io.IOException;
import java.util.ArrayList;
import java.util.List;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;
import net.sf.json.JSONObject;/*** Servlet implementation class GetJSONAarrayData*/
@WebServlet("/GetJSONAarrayData.do")
public class GetJSONAarrayData extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public GetJSONAarrayData() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub//response.getWriter().append("Served at: ").append(request.getContextPath());doPost(request, response);}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub//doGet(request, response);JSONObject object=JSONObject.fromObject(new CodeLanguage(1,"java","Write once,run anywhere"));//第二种方法
// List<CodeLanguage> objArray=new ArrayList<CodeLanguage>();
// objArray.add(new CodeLanguage(1,"java","1"));
// objArray.add(new CodeLanguage(2,"C#","2"));
// JSONArray jsonarray=JSONArray.fromObject(objArray);response.setContentType("text/html;charset=utf-8");response.getWriter().write(object.toString());}}
2.新建一个类CodeLanguage
package com.iflytek.servlet;public class CodeLanguage {private int id;private String test;private String desc;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getTest() {return test;}public void setTest(String test) {this.test = test;}public String getDesc() {return desc;}public void setDesc(String desc) {this.desc = desc;}public CodeLanguage(int id, String test, String desc) {super();this.id = id;this.test = test;this.desc = desc;}public CodeLanguage(){}}
然后运行tomcat进行调试,结果如下图