zoukankan      html  css  js  c++  java
  • 将java的对象或集合转成json形式字符串

     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);
    	}
    }
    

      

     

  • 相关阅读:
    Leetcode 92. Reverse Linked List II
    Leetcode 206. Reverse Linked List
    Leetcode 763. Partition Labels
    Leetcode 746. Min Cost Climbing Stairs
    Leetcode 759. Employee Free Time
    Leetcode 763. Partition Labels
    搭建数据仓库第09篇:物理建模
    Python进阶篇:Socket多线程
    Python进阶篇:文件系统的操作
    搭建数据仓库第08篇:逻辑建模–5–维度建模核心之一致性维度2
  • 原文地址:https://www.cnblogs.com/wuxu/p/10911807.html
Copyright © 2011-2022 走看看