Java Servlet编写Json自定义数据接口

在移动APP独立开发中,很疼苦的一件事就是后台数据接口编写

下面分享一个简单的JSON数据接口编写:

(bean)User类

package bean;

public class User {
	
	public String id;			//用户编号
	public String name;			//用户名称
	public int passwords;		<span style="white-space:pre">	</span>//用户密码
	
	public User(){}
	
	public User(String id,String name,int passwords){
		this.id = id;
		this.name = name;
		this.passwords = passwords;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getPasswords() {
		return passwords;
	}

	public void setPasswords(int passwords) {
		this.passwords = passwords;
	}
}
(Servlet)GetUserServlet服务
package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.util.JSONStringer;
import bean.User;

public class GetUserServlet extends HttpServlet {

	/**
	 * 覆盖Get方法 
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		
		System.out.println("Get方法");
		
		//测试数据
		List<User> list = new ArrayList<User>();
		list.add(new User("U001","张三",123456));
		list.add(new User("U002","李四",654321));
		
		//生成JSON数据
		JSONStringer stringer = new JSONStringer();	  
		JSONObject object = new JSONObject();
		try {  
			stringer.array();  
			for(User u : list) {   
				stringer.object().
				key("Id").value(u.id).  
				key("name").value(u.name).   
				key("passwords").value(u.passwords).
				endObject();  
			}  
			stringer.endArray();
			object.element("user", stringer.toString());
		} catch (Exception e) {  
			e.printStackTrace();  
		}  
		response.getOutputStream().write(object.toString().getBytes("UTF-8"));  
		response.setContentType("text/json; charset=UTF-8"); 
	}

	/**
	 * 跳转到Get方法
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

生产后的JSON数据


Demo下载

http://download.csdn.net/detail/xiaoarea/8712791

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值