java导出json格式化的json文件及xml文件

场景

点击ztree树的节点,导出该节点下的所有子节点数据(要求:导出过程不跳转页面)

前端:

<div id="rolesGroupmenu" class="easyui-menu" style="width:120px">
    <div data-options="iconCls:'icon-export'" onclick="rolesExport()">角色导出</div>
    <div data-options="iconCls:'icon-import'" onclick="roleImport()">角色导入</div>
</div>
	
	<iframe style="display:none;" name="hiddenIframe" id="hiddenIframe"></iframe>

这里用了一个隐藏frame,实现导出的时候不跳转界面 

function rolesExport(){
	var selecnode = getSelectNode();
    if (selecnode != null) {
      var id = selecnode.id;
      var type = selecnode.type;
      var subGuid = selecnode.subGuid;
      var url =ctx_js+"/rolemgr/roles-group/exportRole/"+id+"/"+type+"/"+name+"/"+subGuid;
      //使用iframe进行无跳转页面下载
      $("#hiddenIframe").attr("src", encodeURI(url));
    }
}

后端

@RequestMapping(value = "/exportRole/{id}/{type}/{name}/{subGuid}")
	private void exportRolesData(HttpServletRequest request,HttpServletResponse response,
			@PathVariable String id,@PathVariable String type,
			@PathVariable String name,@PathVariable String subGuid) {
		
    //这里使用了公司封装的远程工具调用rest服务,
    String username = request.getSession().getAttribute("username_") + "";
 		String password = request.getSession().getAttribute("password_") + "";
 		String serviceUrl = Global.getConfig("platform.rest.baseurl") +"/funcmgr/roleExport/"+id+"/"+type+"/"+subGuid;
 		String result = RestUtils.get(serviceUrl, username, password);
		String [] array = result.split(Global.REST_RESPONSE_SPLIT);
		String respBody = array[1];
		//输出json格式的文件
		//ExportFormatUtil.exportJsonArrayFile(response, respBody, name+"-"+ ".json");
		try {
			ExportFormatUtil.exportXmlFile(response, respBody,  name+"-"+ ".xml");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

rest服务


	
	/**
	 * wxy 2021-10-27
	 * 导出子系统或角色组下面的所有数据
	 * @param request
	 * @param id  
	 * @param type 类型
	 * @param subGuid 子系统id
	 * @return
	 */
	@RequestMapping(value="/funcmgr/roleExport/{id}/{type}/{subGuid}",method = RequestMethod.GET,produces = "application/json")
	public List<Map<String, Object>> funcItemExport(HttpServletRequest request,
					                          @PathVariable String id,
					                          @PathVariable String type,
					                          @PathVariable String subGuid){
		
		List<Map<String, Object>> ListresponseMap = new ArrayList<Map<String, Object>>();
		RoleGroup funcGroup =null;
		if("subsystem".equals(type)) {
         //这里先获取子系统下的所有一级角色分组
			List<RoleGroup> list =rolemgrService.createRoleGroupQuery().subGuid(subGuid).list();
			if(!org.springframework.util.ObjectUtils.isEmpty(list)) {
				for (RoleGroup roleGroup : list) {
					if(!StringUtils.isEmpty(roleGroup.getParentId())) {
						Map<String, Object> responseMap = new HashMap<String, Object>();
						responseMap.put("id", roleGroup.getId());
						responseMap.put("name", roleGroup.getName());
						responseMap.put("type", "rolegroup");
						responseMap.put("subGuid", roleGroup.getSubGuid());
                        //每一个角色分组进行递归调用,获取子分组信息
						List<Map<String, Object>> childsList = getAllChilds(roleGroup.getId(),subGuid);
						responseMap.put("childs", childsList);
						ListresponseMap.add(responseMap);
					}
				}
			}
		}else if("rolegroup".equals(type)){
			funcGroup =  rolemgrService.createRoleGroupQuery().id(id).singleResult();
			if(funcGroup != null) {
				Map<String, Object> responseMap = new HashMap<String, Object>();
				responseMap.put("id", id);
				responseMap.put("name", funcGroup.getName());
				responseMap.put("type", "rolegroup");
				responseMap.put("subGuid", funcGroup.getSubGuid());
				List<Map<String, Object>> childsList = getAllChilds(id,subGuid);
				responseMap.put("childs", childsList);
				ListresponseMap.add(responseMap);
			}
		}
		return ListresponseMap;
	}
    
    
	/**
	 * @author maogy 2018-12-06
	   * 获取菜单组下面的所有菜单组和菜单项
	 * @param parentId
	 * @return
	 */
	public List<Map<String, Object>> getAllChilds(String parentId,String subGuid){
		//建立一个集合用来封装树结构
		List<Map<String, Object>> funcGroupTreeList = new ArrayList<Map<String, Object>>();
		//查询下级分组
		List<RoleGroup>  funcGroupList= rolemgrService.createRoleGroupQuery().parentId(parentId).subGuid(subGuid).list();
		if(null != funcGroupList && !funcGroupList.isEmpty()) {
			for(RoleGroup funcGroup:funcGroupList) {
				Map<String, Object> funcGroupMap = new HashMap<String, Object>();
				funcGroupMap.put("id", funcGroup.getId());
				funcGroupMap.put("name", funcGroup.getName());
				funcGroupMap.put("type", "group");
				funcGroupMap.put("subGuid", funcGroup.getSubGuid());
				List<Map<String, Object>> childsList = getAllChilds(funcGroup.getId(),subGuid);
				funcGroupMap.put("childs", childsList);
				funcGroupTreeList.add(funcGroupMap);
			}
		}

		//查询菜单项 
		List<Role> rootItemList = rolemgrService.createRoleQuery().roleGroupId(parentId).subGuid(subGuid).list();
		if(null != rootItemList && !rootItemList.isEmpty()) {
			for(Role funcItem:rootItemList) {
				Map<String, Object> FuncItemMap = new HashMap<String, Object>();
				FuncItemMap.put("id", funcItem.getId());  //名称
				FuncItemMap.put("name", funcItem.getName());  //名称
				FuncItemMap.put("type", "role");
				FuncItemMap.put("subGuid", funcItem.getSubGuid());
				funcGroupTreeList.add(FuncItemMap);
			}
		}		
		return funcGroupTreeList;
	} 

导出工具类

package com.gisquest.platform.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.gisquest.platform.common.utils.FileUtils;

public class ExportFormatUtil {
	
	
	 

    /**
     * 输出json文件
     * @param response response
     * @param jsonArray json数据格式数据,这里数据必须是json数组格式
     * @param fileName fileName
     */
    @SuppressWarnings("resource")
    public static void exportJsonArrayFile(HttpServletResponse response, String jsonArray, String fileName) {
		 Writer bw = null;
         try {
        	 String fullPath = "/" + fileName;
    		 File file = new File(fullPath);
             bw = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
             if (jsonArray != null) {
                 JSONArray etOutputs  = JSON.parseArray(jsonArray);
                 for (int i = 0; i < etOutputs.size(); i++) {
                     JSONObject obj = etOutputs.getJSONObject(i);
                      //输出json格式化数据
                     String pretty = JSON.toJSONString(obj, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                             SerializerFeature.WriteDateUseDateFormat);
                     bw.write(pretty);
                     bw.flush();
                 }
                 bw.close();
         		FileInputStream fis = new FileInputStream(file);
         		// force-download
         		response.setContentType("application/force-download");
         		response.setHeader("Content-Disposition", "attachment;filename="
         				.concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
         		response.setCharacterEncoding("utf-8");
         		OutputStream os = response.getOutputStream();
         		byte[] buf = new byte[1024];
         		int len = 0;
         		while((len = fis.read(buf)) != -1) {
         			os.write(buf, 0, len);
         		}
         		fis.close();
         		os.close();   
             }
         } catch (Exception e) {
             e.printStackTrace();
         } 
    }
   
    /**
     * 输出json文件
     * @param response response
     * @param dataList 输出格式化的json数据,这里数据必须是json格式
     * @param fileName fileName
     */
    public static void exportJsonFile(HttpServletResponse response, String dataList, String fileName){
    	 try {
    		 Map<String,Object> map = new HashMap<String,Object>();
             String jsonString = JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                     SerializerFeature.WriteDateUseDateFormat);
             String fullPath = "/" + fileName;
             File file = new File(fullPath);
             Writer write = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
             write.write(jsonString);
             write.flush();
             write.close();

             FileInputStream fis = new FileInputStream(file);
             // force-download
             response.setContentType("application/force-download");
             response.setHeader("Content-Disposition", "attachment;filename="
                     .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
             response.setCharacterEncoding("utf-8");

             OutputStream os = response.getOutputStream();
             byte[] buf = new byte[1024];
             int len = 0;
             while((len = fis.read(buf)) != -1) {
                 os.write(buf, 0, len);
             }
             fis.close();
             os.close();

         } catch (Exception e) {
             e.printStackTrace();
         }
     }

    
    /**
     * 输出xml文件
     * @param response response
     * @param jsonArray  格式要求:list<Map>的字符串格式
     * @param fileName fileName
     */
	public  static void exportXmlFile(HttpServletResponse response, String jsonArray, String fileName) throws IOException, IOException{
		String fullPath = "/测试" ;
		File xmlFile = new File(fullPath);
		List<Map> fileList =JSON.parseArray(jsonArray, Map.class);
		createXmlFile(xmlFile,fileList);
		try {
			     FileInputStream fis = new FileInputStream(xmlFile);
	             // force-download
	             response.setContentType("application/force-download");
	             response.setHeader("Content-Disposition", "attachment;filename="
	                     .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
	             response.setCharacterEncoding("utf-8");

	             OutputStream os = response.getOutputStream();
	             byte[] buf = new byte[1024];
	             int len = 0;
	             while((len = fis.read(buf)) != -1) {
	                 os.write(buf, 0, len);
	             }
	             fis.close();
	             os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	} 
	
	

	public static  void createXmlFile(File xmlFile, List<Map> childList2) throws IOException, IOException{
		Element root  = DocumentHelper.createElement("root");
		for(Map<String, Object> fileMap:childList2) {
			Iterator<Map.Entry<String, Object>> it = fileMap.entrySet().iterator();
			if(fileMap.get("type")!=null) {
					/*fileMap.get("type").equals("group")*/
				Element element = root.addElement("div");
				while(it.hasNext()) {
					Map.Entry<String, Object> entry = it.next();
					if(entry.getKey().equals("childs")) {
						List<Map> childList = (List<Map>) entry.getValue();
						if(childList != null && !childList.isEmpty()) {
							Element element1 = element.addElement("childs");
							createXmlFile(xmlFile,childList);
						}
					}else {
						element.addElement(entry.getKey()).addText(entry.getValue()==null?"":entry.getValue()+"");
					}
				}
			}else {
				while(it.hasNext()) {
					Map.Entry<String, Object> entry = it.next();
					root.addElement(entry.getKey()).addText(entry.getValue()+"");
				}
			}
		}
		org.dom4j.io.OutputFormat format = new org.dom4j.io.OutputFormat();  
		format.setEncoding("UTF-8");//设置编码格式  
		XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(xmlFile),format);
		xmlWriter.write(root);
		xmlWriter.close();
	} 
	
}

postman测试rest服务

192.168.100.88:8082/GisqPlatformDesigner-Rest/service/funcmgr/roleExport/609273de-8312-11e7-9c1a-fa163e2a6242/subsystem/491a74fd-8312-11e7-9c1a-fa163e2a6242
[
    {
        "subGuid": "491a74fd-8312-11e7-9c1a-fa163e2a6242",
        "name": "开发组",
        "id": "69c382af-8312-11e7-9c1a-fa163e2a6242",
        "type": "rolegroup",
        "childs": [
            {
                "subGuid": "491a74fd-8312-11e7-9c1a-fa163e2a6242",
                "name": "aa",
                "id": "02b99d0c-4aa8-11e8-8f36-fa163e2a6242",
                "type": "role"
            },
            {
                "subGuid": "491a74fd-8312-11e7-9c1a-fa163e2a6242",
                "name": "测试",
                "id": "4a1c4bb1-cf49-11e7-97de-fa163e2a6242",
                "type": "role"
            },
            {
                "subGuid": "491a74fd-8312-11e7-9c1a-fa163e2a6242",
                "name": "pro_new",
                "id": "74ebbe7a-4ab6-11e8-8f36-fa163e2a6242",
                "type": "role"
            },
            {
                "subGuid": "491a74fd-8312-11e7-9c1a-fa163e2a6242",
                "name": "开发",
                "id": "77488250-8312-11e7-9c1a-fa163e2a6242",
                "type": "role"
            },
            {
                "subGuid": "491a74fd-8312-11e7-9c1a-fa163e2a6242",
                "name": "新",
                "id": "d775a9b8-49b9-11e8-8f36-fa163e2a6242",
                "type": "role"
            }
        ]
    },
    {
        "subGuid": "491a74fd-8312-11e7-9c1a-fa163e2a6242",
        "name": "潘怡成学习",
        "id": "f39b319f-3b1f-11e9-a8a7-50465d555ba3",
        "type": "rolegroup",
        "childs": [
            {
                "subGuid": "491a74fd-8312-11e7-9c1a-fa163e2a6242",
                "name": "学习",
                "id": "00640d30-3b20-11e9-a8a7-50465d555ba3",
                "type": "role"
            }
        ]
    }
]

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值