package servlet;
import entity.Users;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JsonServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
Users users = new Users("张三", "q123");
//将Users对象转换为JSONObject
JSONObject jsonObject = JSONObject.fromObject(users);
//使用JSONObject的toString()方法将JSONObject转换成字符串
System.out.println( "users:" + jsonObject.toString() );
List<String> listStr = new ArrayList<String>(0);
listStr.add("小明");
listStr.add("小红");
JSONArray jsonListStr = JSONArray.fromObject(listStr);
System.out.println( "jsonListStr:" + jsonListStr.toString() );
List<Users> listUsers = new ArrayList<Users>(0);
listUsers.add(new Users("大名", "123"));
listUsers.add(new Users("大红", "456"));
JSONArray jsonListUsers = JSONArray.fromObject(listUsers);
System.out.println( "jsonListUsers:" + jsonListUsers.toString() );
Map<String, String> mapStr = new HashMap<String, String>(0);
mapStr.put("彩虹", "彩彩");
mapStr.put("豆豆", "小豆");
JSONObject jsonMapStr = JSONObject.fromObject(mapStr);
System.out.println( "jsonMapStr:" + jsonMapStr.toString() );
Map<String, Users> mapUser = new HashMap<String, Users>(0);
mapUser.put("1", new Users("小彩虹", "123"));
mapUser.put("2", new Users("小豆豆", "123"));
JSONObject jsonMapUser = JSONObject.fromObject(mapUser);
System.out.println( "jsonMapUser:" + jsonMapUser.toString() );
Map<String, Object> result = new HashMap<String, Object>(0);
result.put("jsonListStr", jsonListStr);
result.put("jsonListUsers", jsonListUsers);
result.put("jsonMapStr", jsonMapStr);
result.put("jsonMapUser", jsonMapUser);
result.put("users", jsonObject);
JSONObject jsonResult = JSONObject.fromObject(result);
System.out.print(jsonResult.toString());
response.getWriter().print(jsonResult.toString());
}
}
评论0
最新资源