java解析xml文件数据到json对象或实体类对象

2019-04-26 10:59:14  卢浮宫  版权声明:本文为站长原创文章,转载请写明出处



一、背景

    最近做接口对接,数据返回是一个zip的文件流数据(后面会有一篇文章记录),需要进行数据解析,这里记录下


二、读取xml数据

    执行接口网络请求后获取到zip文件流数据,并调用解析方法

    InputStream instreams = entity.getContent();
   转换成文件并保存到本地(这里并且返回了文件名用以后续读取)
   String fileName = ZipUtil.upload(instreams,"D:\\\\pengpeng");

三、ZIPUtil工具类部分代码

 ZipUtil代码如下:
    package com.xmy.pengpeng.Util;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.InflaterInputStream;
import java.util.zip.ZipInputStream;
public class ZipUtil {
public static String upload(InputStream input,String destPath) throws Exception {
ZipInputStream zis = new ZipInputStream(input);
java.util.zip.ZipEntry entry = null;
String[] names = new String[0];
while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory()) {
File f = new File(destPath + File.separator + entry.getName());
if (!f.exists()) {
f.mkdirs();
}
} else {
byte[] data = getByte(zis);
InputStream is = new ByteArrayInputStream(data); // 把当前条目的字节数据转换成Inputstream流
names = entry.getName().split("/");
String path = destPath + File.separator;
path += join(names, File.separator);
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}else{
file.delete();
}
toWrite(is, file);
}
}
return names[0];
}

/**
* 向file文件写入字节
* @param ins
* @param file
*/
public static void toWrite(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 获取条目byte[]字节
* @param zis
* @return
*/
public static byte[] getByte(InflaterInputStream zis) {
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] temp = new byte[1024];
byte[] buf = null;
int length = 0;
while ((length = zis.read(temp, 0, 1024)) != -1) {
bout.write(temp, 0, length);
}
buf = bout.toByteArray();
bout.close();
return buf;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static String join(Object[] o, String flag) {
StringBuffer str_buff = new StringBuffer();
for (int i = 0, len = o.length; i < len; i++) {
str_buff.append(String.valueOf(o[i]));
if (i < len - 1) {
str_buff.append(flag);
}
}
return str_buff.toString();
}
}


四、格式化xml数据为实体类或json对象

    PS:(xml支持直接转成实体类对象,也可以先转成JSONObject在转成实体类,但是后者效率太低不推荐使用)

  XmlDataAny代码段如下:       

    package com.xmy.pengpeng.Util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.thoughtworks.xstream.XStream;
import com.xmy.pengpeng.Model.Policy;
import com.xmy.pengpeng.Model.Response;
import com.xmy.pengpeng.Model.TestModel;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import javax.xml.bind.JAXBException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.io.*;

/**
*@Author: Administrator on 2019/4/25 14:49
*@param:
*@return:
*@Description:xml数据格式化处理
**/
public class XmlDataAny {

// @Autowired
// private MongoTemplate mongoTemplate;

//获取xml文件数据方法入口
public void dataFormatXml(String fileName,MongoTemplate mongoTemplate) throws IOException, JDOMException, JAXBException {
getXmlStr(fileName,mongoTemplate);
}

//获取xml数据
private void getXmlStr(String fileName,MongoTemplate mongoTemplate) throws IOException, JDOMException, JAXBException {
String rltStr = "";
FileInputStream fis = new FileInputStream("D:\\pengpeng\\" + fileName);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] bt = new byte[1024];
int len;
while ((len = bis.read(bt))!= -1) {
String strTmp = new String(bt,0,len);
rltStr+= strTmp;
}
bis.close();
fis.close();
rltStr = rltStr.replace("\n","");
doSave(rltStr,mongoTemplate);
//下面是xml数据转换成json的代码段
// JSONObject rltObj = xmlToJSON(rltStr.getBytes());
// //格式化obj转换成实体类
// dataFormatpolicyObj(rltObj,mongoTemplate);
}

private void doSave(String xmlStr,MongoTemplate mongoTemplate){
Policy policy = new Policy();
XStream xstream = new XStream();
xstream.alias("response", Response.class);
xstream.alias("policy", Policy.class);
Response response = (Response)xstream.fromXML(xmlStr);
List<Policy> policyList = response.getPolicyList();
for(int i=0;i<policyList.size();i++){
policy = policyList.get(i);
mongoTemplate.save(policy);
}
}

public static JSONObject xmlToJSON(byte[] xml) throws JDOMException, IOException {
JSONObject json = new JSONObject();
InputStream is = new ByteArrayInputStream(xml);
SAXBuilder sb = new SAXBuilder();
org.jdom2.Document doc = sb.build(is);
Element root = doc.getRootElement();
json.put(root.getName(), iterateElement(root));
return json;
}

private static JSONObject iterateElement(Element element) {
List node = element.getChildren();
Element et = null;
JSONObject obj = new JSONObject();
List list = null;
for (int i = 0; i < node.size(); i++) {
list = new LinkedList();
et = (Element) node.get(i);
if (et.getTextTrim().equals("")) {
if (et.getChildren().size() == 0) {
continue;
}
if (obj.containsKey(et.getName())) {
list = (List) obj.get(et.getName());
}
list.add(iterateElement(et));
obj.put(et.getName(), list);
} else {
if (obj.containsKey(et.getName())) {
list = (List) obj.get(et.getName());
}
list.add(et.getTextTrim());
obj.put(et.getName(), list);
}
}
return obj;
}
private void dataFormatpolicyObj(JSONObject pObj,MongoTemplate mongoTemplate){
Policy policy = new Policy();
List<Policy> policyList = new ArrayList<Policy>();
JSONObject obj = JSON.parseObject(pObj.get("response").toString());
JSONArray policyArr = JSON.parseArray(obj.get("policyList").toString());
JSONObject policyListobj = JSON.parseObject(policyArr.get(0).toString());
JSONArray polucyList = JSON.parseArray(policyListobj.get("policy").toString());
String businessNo = obj.get("businessNo").toString();
String uploadType = obj.get("uploadType").toString();
String productType = obj.get("productType").toString();
for (int i=0;i<polucyList.size();i++){
String strTmp = JSONObject.toJSONString(polucyList.get(i)).replace("[","").replace("]","");
policy = JSON.parseObject(strTmp,policy.getClass());
policy.setCreateDate(DateUtil.getNowDateTime());
mongoTemplate.save(policy);
}
}
}


五、附需要用的maven配置    

    
        <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>

<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.5</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.9</version>
</dependency>





更多精彩请关注guangmuhua.com


最新评论: