使用jaxb进行xml到bean的转换(尝试解决空值不显示问题)

import javax.xml.bind.Marshaller;
import java.lang.reflect.Field;
//监听生成xml文件过程
public class MarshallerListener extends Marshaller.Listener {

    public static final String BLANK_CHAR = "";

    @Override
    public void beforeMarshal(Object source) {
        super.beforeMarshal(source);
        Field[] fields = source.getClass().getDeclaredFields();
        for (Field f : fields) {
            f.setAccessible(true);
            try {
                System.out.println(f.getType() + f.getName());
                if (f.getType() == String.class && f.get(source) == null) {
                    f.set(source, BLANK_CHAR);
                }else if(!isBaseType(f)&& f.get(source) != null){
                    beforeMarshalClass(f.get(source));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
    
    private void beforeMarshalClass(Object source) {
        // TODO Auto-generated method stub
        Field[] fields = source.getClass().getDeclaredFields();
        for (Field f : fields) {
            f.setAccessible(true);
            try {
                if (f.getType() == String.class && f.get(source) == null) {
                    f.set(source, BLANK_CHAR);
                }else if(!isBaseType(f) && f.get(source) != null){
                    System.out.println(f.getType()+f.getName());
                    beforeMarshalClass(f.get(source));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    /**
    * 判断object是否为基本类型
    * @param object
    * @return
    */
    public static boolean isBaseType(Field f) {
        System.out.println(f.getType());
        System.out.println(String.class);
        System.out.println(f.getType() == String.class);
        if (f.getType() == Integer.class ||
            f.getType() == Byte.class ||
            f.getType() == Long.class ||
            f.getType() == Double.class ||
            f.getType() == String.class ||
            f.getType() == Float.class ||
            f.getType() == Character.class ||
            f.getType() == Short.class ||
            f.getType() == Boolean.class) {
            return true;
        }
        return false;
    }
}
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;


public class JaxbUtil {//工具类

    /**
     * java对象转换为xml文件
     * @param xmlPath  xml文件路径
     * @param load    java对象.Class
     * @return    xml文件的String
     * @throws JAXBException    
     */
    public static String beanToXml(Object obj, Class<?> load) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(load);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        StringWriter writer = new StringWriter();
        marshaller.marshal(obj, writer);
        return writer.toString();
    }

    /**
     * xml文件配置转换为对象
     * @param xmlPath  xml文件路径
     * @param load    java对象.Class
     * @return    java对象
     * @throws JAXBException    
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public static <T> T xmlToBean(String xmlPath, Class<T> load) throws JAXBException, IOException {
        JAXBContext context = JAXBContext.newInstance(load);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        return (T) unmarshaller.unmarshal(new StringReader(xmlPath));
    }
    
    /** 
     * JavaBean转换成xml 
     * 默认编码UTF-8 
     * @param obj 
     * @param writer 
     * @return  
     */
    public static String convertToXml(Object obj) {
        return convertToXml(obj, "UTF-8");
    }

    /** 
     * JavaBean转换成xml 
     * @param obj 
     * @param encoding  
     * @return  
     */
    public static String convertToXml(Object obj, String encoding) {
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            marshaller.setListener(new MarshallerListener());
            
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            result = writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
    
    /** 
     * JavaBean转换成xml去除xml声明部分 
     * @param obj 
     * @param encoding  
     * @return  
     */
    public static String convertToXmlIgnoreXmlHead(Object obj, String encoding) {
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            result = writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
    
    
    

    /** 
     * xml转换成JavaBean 
     * @param xml 
     * @param c 
     * @return 
     */
    @SuppressWarnings("unchecked")
    public static <T> T converyToJavaBean(String xml, Class<T> c) {
        T t = null;
        try {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            t = (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return t;
    }

}

生成xml的demo

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class XmlUtil {

    private final static Logger logger = LoggerFactory.getLogger(MsBusUtil.class);

    public final static String msBus_xmlns = "http://MSBUSPlatform/v2.0";

    /**
     * Add RequestHead to Request, Invoke, and remove ResponseHead from Response
     * 
     * @param strRequestParam String
     * @param strSvcName      String
     * @param strSvcMethod    String
     * @return String
     * @throws GeneralException
     */
    public static String invokeParam(String strRequestParam, String strSvcID, String keyword) throws DocumentException {

        Document doc = DocumentHelper.createDocument();
        Element elmRoot = doc.addElement("ServiceInvoke", MsBusUtil.msBus_xmlns);
        Element elmHead = elmRoot.addElement("RequestHead");
        elmHead.addElement("Requestid").addText(getRequestID(strSvcID));
        elmHead.addElement("Requesttime").addText(DateUtil.getNowStr());
        elmHead.addElement("Sourcesystemid").addText("");
        elmRoot.addElement("Serviceid").addText(strSvcID);
        elmParam.addCDATA(strRequestParam);
        elmRoot.addElement("Keyword").addText(keyword);

        String strRequest = StringTranslator.toString(doc, "UTF-8");
        logger.info("invoke Request:" + strRequest);
        return strRequest;
    }

    public static String getRequestID(String strSvcID) throws DocumentException {
        RandomGUID randomGUID = new RandomGUID();
        return  strSvcID + "-" + randomGUID.toString();
    }

    public static void main(String[] args) throws Throwable {
        UnifiedContentDefineType ucd = new UnifiedContentDefineType();
        ucd.setHead(new HeadType());
        String param = JaxbUtil.convertToXml(ucd, "utf-8");
                
        String req = invokeParam(param, "PLATFORM-UnifiedImport", "测试一下");
        string2File(req,"F:\归档.xml");
    };

    /**
     * 文本文件转换为指定编码的字符串
     * 
     * @param file     文本文件
     * @param encoding 编码类型
     * @return 转换后的字符串
     * @throws IOException
     */
    public static String file2String(File file, String encoding) {
        InputStreamReader reader = null;
        StringWriter writer = new StringWriter();
        try {
            if (encoding == null || "".equals(encoding.trim())) {
                reader = new InputStreamReader(new FileInputStream(file), encoding);
            } else {
                reader = new InputStreamReader(new FileInputStream(file));
            }
            // 将输入流写入输出流
            char[] buffer = new char[1024];
            int n = 0;
            while (-1 != (n = reader.read(buffer))) {
                writer.write(buffer, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return writer.toString();
    }
    
    /** 
     * 将字符串写入指定文件(当指定的父路径中文件夹不存在时,会最大限度去创建,以保证保存成功!) 
     * 
     * @param res            原字符串 
     * @param filePath 文件路径 
     * @return 成功标记 
     */ 
    public static boolean string2File(String res, String filePath) { 
            boolean flag = true; 
            BufferedReader bufferedReader = null; 
            BufferedWriter bufferedWriter = null; 
            try { 
                    File distFile = new File(filePath); 
                    if (!distFile.getParentFile().exists()) distFile.getParentFile().mkdirs(); 
                    bufferedReader = new BufferedReader(new StringReader(res)); 
                    bufferedWriter = new BufferedWriter(new FileWriter(distFile)); 
                    char buf[] = new char[1024];         //字符缓冲区 
                    int len; 
                    while ((len = bufferedReader.read(buf)) != -1) { 
                            bufferedWriter.write(buf, 0, len); 
                    } 
                    bufferedWriter.flush(); 
                    bufferedReader.close(); 
                    bufferedWriter.close(); 
            } catch (IOException e) { 
                    e.printStackTrace(); 
                    flag = false; 
                    return flag; 
            } finally { 
                    if (bufferedReader != null) { 
                            try { 
                                    bufferedReader.close(); 
                            } catch (IOException e) { 
                                    e.printStackTrace(); 
                            } 
                    } 
            } 
            return flag; 
    }

}
原文地址:https://www.cnblogs.com/liangblog/p/12803910.html