javaEE Json序列化, jsonlib, Gson

常用的json转换(序列化)工具有如下几种:
1)jsonlib:sun公司
2)Gson:google
3)fastjson:阿里巴巴 (推荐)

Jar包下载:https://pan.baidu.com/s/1J6XHPuoJYtjD5X5jENs_fQ  密码:xqi3


DemoServlet.java:

package com.xxx.web;

import java.io.IOException;

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

import com.google.gson.Gson;

import net.sf.json.JSONArray;

public class DemoServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		
		//..................
		//使用json的转换工具将对象或集合转成json格式的字符串
		// 1、jsonlib工具完成json序列化
		JSONArray array = JSONArray.fromObject(productList);  // productList是要序列化的JavaBean的List。
		String jsonStr = array.toString();
		
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write(jsonStr);
		
		//*************************************************
		// 2、Gson工具完成json序列化
		Gson gson = new Gson();
		String json = gson.toJson(productList);
		
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write(json);
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);
	}
}


猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/80904485