将java的对象或集合转成json形式字符串

博客介绍了将Java对象或集合转换为JSON形式字符串的方法,借助Java工具和JSON转换插件实现。还列举了常用的JSON转换工具,如jsonlib、Google的Gson、阿里巴巴的fastjson,并给出了相关参考链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 java的对象或集合转成json形式字符串:

json的转换插件是通过java的一些工具,直接将java对象或集合转换成json字符串。

常用的json转换工具有如下几种:

1)jsonlib

需要导入以下包:

2)Gsongoogle

需要导入一下包 

 

3)fastjson:阿里巴巴

 

package com.itheima.web;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

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 com.itheima.domain.Product;
import com.itheima.service.ProductService;

import net.sf.json.JSONArray;
import sun.org.mozilla.javascript.internal.json.JsonParser;

public class SearchWordServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//获得关键字
		String word = request.getParameter("word");
		
		//查询该关键字的所有商品
		ProductService service = new ProductService();
		List<Object> productList = null;
		try {
			productList = service.findProductByWord(word);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		//["xiaomi","huawei",""...]
		
		//使用json的转换工具将对象或集合转成json格式的字符串    jsonlib工具
		/*JSONArray fromObject = JSONArray.fromObject(productList);
		String string = fromObject.toString();
		System.out.println(string);*/
		//Gson工具
		Gson gson = new Gson();
		String json = gson.toJson(productList);
		System.out.println(json);
		
		response.setContentType("text/html;charset=UTF-8");
		
		response.getWriter().write(json);
		
		
	}

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

  

 

转载于:https://www.cnblogs.com/wuxu/p/10911807.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值