为什么要用fastjson
如果手上有一个对象集合
要返回数据时拼json字符串很麻烦
示例代码
```go
package servlet;
import bean.Student;
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 java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/student_list")
public class StudentList extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 说到
resp.setHeader("Content-Type", "text/html;charset=utf-8");
// 做到
resp.setCharacterEncoding("utf-8");
// 模拟得到对象集合
List<Student> studentList = getStudentList();
// 返回json数据给前端
// [{"name":"张三","age":16},{"name":"李四","age":22},{"name":"张三","age":16},]
// json字符串
String jsonStr = "";
jsonStr += "[";
for (Student s : studentList
) {
String fmt = "{\"name\":\"%s\",\"age\":%s}";
String d = String.format(fmt, s.getName(), s.getAge()); // {"name":"张三","age":16}
jsonStr += d;
jsonStr += ",";
}
jsonStr = jsonStr.substring(0, jsonStr.length() - 1);
jsonStr += "]";
System.out.println(jsonStr);
// 返回数据
PrintWriter writer = resp.getWriter();
writer.write(jsonStr);
}
private List<Student> getStudentList() {
// 模拟返回数据
// 对象集合
List<Student> studentList = new ArrayList<>();
// 新建对象,设置属性
Student xm = new Student();
xm.setName("小明");
xm.setAge(16);
Student xh = new Student();
xh.setName("小红");
xh.setAge(26);
// 把对象添加到集合中
studentList.add(xm);
studentList.add(xh);
// 返回集合
return studentList;
}
}
使用fastjson一行代码解决问题
下载信息
文件名:
fastjson20220521