开发者社区> 问答> 正文

JAXB 如何序列化List<Map<String, String>>

bean结构简单如下 Java代码 收藏代码

public class User {  
    private int count;  
    private List<Map<String, String>> rows;  
          
}

getter、setter省略 如何才能序列化成下面的格式 Java代码 收藏代码

<user>  
    <count></count>  
    <rows>  
        <row>  
            <id></id>  
            <name></name>  
        </row>  
        <row>  
            <id></id>  
            <name></name>  
        </row>  
    </rows>  
<user>

其中id、name为Map中的Key。 望各位不吝赐教,谢谢

展开
收起
长安归故里. 2020-01-07 21:03:41 1203 0
1 条回答
写回答
取消 提交回答
  • Java代码 收藏代码

    import java.io.StringReader;  
    import java.io.StringWriter;  
    import java.util.ArrayList;  
    import java.util.HashMap;  
    import java.util.List;  
    import java.util.Map;  
    import java.util.Map.Entry;  
      
    import javax.xml.bind.JAXBContext;  
    import javax.xml.bind.JAXBException;  
    import javax.xml.bind.annotation.XmlAccessType;  
    import javax.xml.bind.annotation.XmlAccessorType;  
    import javax.xml.bind.annotation.XmlElement;  
    import javax.xml.bind.annotation.XmlRootElement;  
    import javax.xml.bind.annotation.adapters.XmlAdapter;  
    import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;  
    import javax.xml.parsers.DocumentBuilder;  
    import javax.xml.parsers.DocumentBuilderFactory;  
      
    import org.w3c.dom.Document;  
    import org.w3c.dom.Element;  
    import org.w3c.dom.Node;  
    import org.w3c.dom.NodeList;  
      
    @XmlRootElement(name = "user")  
    @XmlAccessorType(XmlAccessType.FIELD)  
    public class User {  
      
        /** 
         *  
         *JAXB XML适配器 
         * 
         */  
        public static class UserRowsXmlAdapter extends  
                XmlAdapter<Object, List<Map<String, String>>> {  
      
            /** 
             * 把 JAVA转化成ELEMENT对象 
             */  
            @Override  
            public Object marshal(List<Map<String, String>> rows) throws Exception {  
      
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
                DocumentBuilder db = dbf.newDocumentBuilder();  
                Document document = db.newDocument();  
                Element rootElement = document.createElement("myrows");// 这里名字随便,以外面为准,JAXB会自动替换名字的  
                document.appendChild(rootElement);  
      
                for (Map<String, String> row : rows) {  
      
                    Element rowEle = document.createElement("row");  
      
                    Element idEle = document.createElement("id");  
                    Element nameEle = document.createElement("name");  
      
                    Entry<String, String> entry = row.entrySet().iterator().next();// 第一个ENTRY  
                    String id = entry.getKey();// ID  
                    String name = entry.getValue();// NAME  
      
                    idEle.setTextContent(id);  
                    nameEle.setTextContent(name);  
                    rowEle.appendChild(idEle);  
                    rowEle.appendChild(nameEle);  
                    rootElement.appendChild(rowEle);  
                }  
                return rootElement;  
            }  
      
            /** 
             * 把XML ELEMENT转化成JAVA对象 
             */  
            @Override  
            public List<Map<String, String>> unmarshal(Object rowsElement)  
                    throws Exception {  
      
                if (rowsElement == null) {  
                    return null;  
                }  
      
                Element rowsEle = (Element) rowsElement;  
      
                NodeList rowNodes = rowsEle.getChildNodes();  
                int rowCount = (rowNodes == null ? 0 : rowNodes.getLength());  
                if (rowCount == 0) {  
                    return null;  
                }  
                List<Map<String, String>> result = new ArrayList<Map<String, String>>(  
                        rowCount);  
      
                for (int i = 0; i < rowCount; i++) {  
                    Node rowNode = rowNodes.item(i);  
                    if (!"row".equals(rowNode.getNodeName())) {  
                        System.out.println("发现非法节点:" + rowNode.getNodeName()  
                                + "忽略.");  
                        continue;  
                    }  
                    NodeList idNameNodes = rowNode.getChildNodes();  
                    int nodeSize = (idNameNodes == null ? 0 : idNameNodes  
                            .getLength());  
                    if (nodeSize == 0) {  
                        continue;  
                    }  
                    Map<String, String> row = new HashMap<String, String>();  
                    String id = null;  
                    String name = null;  
                    for (int j = 0; j < nodeSize; j++) {  
                        Node node = idNameNodes.item(j);  
                        String nodeName = node.getNodeName();  
                        String nodeValue = node.getTextContent();  
                        if ("id".equals(nodeName)) {  
                            id = nodeValue;  
                        } else if ("name".equals(nodeName)) {  
                            name = nodeValue;  
                        }  
                        if (id != null && name != null) {  
                            break;  
                        }  
                    }  
      
                    if (id != null) {  
                        row.put(id, name);  
                    } else {  
                        System.out.println("未在row节点里发现id节点,忽略.");  
                    }  
                    result.add(row);  
                }  
      
                return result;  
            }  
      
        }  
          
        @XmlElement(name="count")  
        private int count;  
        @XmlElement(name="rows")  
        @XmlJavaTypeAdapter(UserRowsXmlAdapter.class)  
        private List<Map<String, String>> rows;  
      
        public int getCount() {  
            return count;  
        }  
      
        public void setCount(int count) {  
            this.count = count;  
        }  
      
        public List<Map<String, String>> getRows() {  
            return rows;  
        }  
      
        public void setRows(List<Map<String, String>> rows) {  
            this.rows = rows;  
        }  
      
        @Override  
        public String toString() {  
            return "User [count=" + count + ", rows=" + rows + "]";  
        }  
      
        public static void main(String[] args) throws JAXBException {  
            User u = new User();  
            List<Map<String, String>> rows = new ArrayList<Map<String, String>>(2);  
            Map<String, String> row = new HashMap<String, String>();  
            row.put("1", "土豆");// userid=1,username=土豆  
            rows.add(row);  
            row = new HashMap<String, String>();  
            row.put("2", "洋葱");// userid=2,username=洋葱  
            rows.add(row);  
            u.setCount(rows.size());  
            u.setRows(rows);  
      
            JAXBContext jc = JAXBContext.newInstance(User.class);  
            StringWriter writer = new StringWriter();  
            jc.createMarshaller().marshal(u, writer);  
            System.out.println("Marshalled xml==>");  
            System.out.println(writer);  
            String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"  
                    + "<user><count>2</count><rows><row><id>1</id><name>土豆</name>"  
                    + "</row><row><id>2</id><name>洋葱</name>"  
                    + "</row></rows></user>";  
      
            User newu = (User) jc.createUnmarshaller().unmarshal(  
                    new StringReader(xml));  
            System.out.println("UnMarshalled user==>");  
            System.out.println(newu);  
        }  
      
    }
    
    

    输出结果:

    Java代码 收藏代码

    Marshalled xml==>  
      
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?><user><count>2</count><rows><row><id>1</id><name>土豆</name></row><row><id>2</id><name>洋葱</name></row></rows></user>  
      
    UnMarshalled user==>  
      
    User [count=2, rows=[{1=土豆}, {2=洋葱}]]
    
    2020-01-07 21:04:07
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载