栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

场景

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

前端:

    角色导出
    角色导入

	
	

这里用了一个隐藏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服务

	
	
	@RequestMapping(value="/funcmgr/roleExport/{id}/{type}/{subGuid}",method = RequestMethod.GET,produces = "application/json")
	public List> funcItemExport(HttpServletRequest request,
					                          @PathVariable String id,
					                          @PathVariable String type,
					                          @PathVariable String subGuid){
		
		List> ListresponseMap = new ArrayList>();
		RoleGroup funcGroup =null;
		if("subsystem".equals(type)) {
         //这里先获取子系统下的所有一级角色分组
			List list =rolemgrService.createRoleGroupQuery().subGuid(subGuid).list();
			if(!org.springframework.util.ObjectUtils.isEmpty(list)) {
				for (RoleGroup roleGroup : list) {
					if(!StringUtils.isEmpty(roleGroup.getParentId())) {
						Map responseMap = new HashMap();
						responseMap.put("id", roleGroup.getId());
						responseMap.put("name", roleGroup.getName());
						responseMap.put("type", "rolegroup");
						responseMap.put("subGuid", roleGroup.getSubGuid());
                        //每一个角色分组进行递归调用,获取子分组信息
						List> 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 responseMap = new HashMap();
				responseMap.put("id", id);
				responseMap.put("name", funcGroup.getName());
				responseMap.put("type", "rolegroup");
				responseMap.put("subGuid", funcGroup.getSubGuid());
				List> childsList = getAllChilds(id,subGuid);
				responseMap.put("childs", childsList);
				ListresponseMap.add(responseMap);
			}
		}
		return ListresponseMap;
	}
    
    
	
	public List> getAllChilds(String parentId,String subGuid){
		//建立一个集合用来封装树结构
		List> funcGroupTreeList = new ArrayList>();
		//查询下级分组
		List  funcGroupList= rolemgrService.createRoleGroupQuery().parentId(parentId).subGuid(subGuid).list();
		if(null != funcGroupList && !funcGroupList.isEmpty()) {
			for(RoleGroup funcGroup:funcGroupList) {
				Map funcGroupMap = new HashMap();
				funcGroupMap.put("id", funcGroup.getId());
				funcGroupMap.put("name", funcGroup.getName());
				funcGroupMap.put("type", "group");
				funcGroupMap.put("subGuid", funcGroup.getSubGuid());
				List> childsList = getAllChilds(funcGroup.getId(),subGuid);
				funcGroupMap.put("childs", childsList);
				funcGroupTreeList.add(funcGroupMap);
			}
		}

		//查询菜单项 
		List rootItemList = rolemgrService.createRoleQuery().roleGroupId(parentId).subGuid(subGuid).list();
		if(null != rootItemList && !rootItemList.isEmpty()) {
			for(Role funcItem:rootItemList) {
				Map FuncItemMap = new HashMap();
				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 {
	
	
	 

    
    @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();
         } 
    }
   
    
    public static void exportJsonFile(HttpServletResponse response, String dataList, String fileName){
    	 try {
    		 Map map = new HashMap();
             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();
         }
     }

    
    
	public  static void exportXmlFile(HttpServletResponse response, String jsonArray, String fileName) throws IOException, IOException{
		String fullPath = "/测试" ;
		File xmlFile = new File(fullPath);
		List 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 childList2) throws IOException, IOException{
		Element root  = documentHelper.createElement("root");
		for(Map fileMap:childList2) {
			Iterator> it = fileMap.entrySet().iterator();
			if(fileMap.get("type")!=null) {
					
				Element element = root.addElement("div");
				while(it.hasNext()) {
					Map.Entry entry = it.next();
					if(entry.getKey().equals("childs")) {
						List childList = (List) 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 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"
            }
        ]
    }
]

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/353754.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号