Simplest method to Convert Json to Xml

前端 未结 5 1615
挽巷
挽巷 2020-12-06 05:12

I have web-service in .net. When I retrieve data from database, it returns JSON File in Android Mobile. How can I convert JSON File to XML Or text.

5条回答
  •  抹茶落季
    2020-12-06 05:57

    Here is an example of how you can do this, generating valid XML. I also use the Jackson library in a Maven project.

    Maven setup:

    
        
            com.fasterxml
            jackson-xml-databind
            0.6.2
        
        
        
            com.fasterxml.jackson.core
            jackson-databind
            2.8.6
        
    

    Here is some Java code that first converts a JSON string to an object and then converts the object with the XMLMapper to XML and also removes any wrong element names. The reason for replacing wrong characters in XML element names is the fact that you can use in JSON element names like $oid with characters not allowed in XML. The Jackson library does not account for that, so I ended up adding some code which removes illegal characters from element names and also the namespace declarations.

    import com.fasterxml.jackson.core.type.TypeReference;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.xml.XmlMapper;
    
    import java.io.IOException;
    import java.util.Map;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    /**
     * Converts JSON to XML and makes sure the resulting XML 
     * does not have invalid element names.
     */
    public class JsonToXMLConverter {
    
        private static final Pattern XML_TAG =
                Pattern.compile("(?m)(?s)(?i)(?<(/)?)(?.+?)(?(/)?>)");
    
        private static final Pattern REMOVE_ILLEGAL_CHARS = 
                Pattern.compile("(i?)([^\\s=\"'a-zA-Z0-9._-])|(xmlns=\"[^\"]*\")");
    
        private ObjectMapper mapper = new ObjectMapper();
    
        private XmlMapper xmlMapper = new XmlMapper();
    
        String convertToXml(Object obj) throws IOException {
            final String s = xmlMapper.writeValueAsString(obj);
            return removeIllegalXmlChars(s);
        }
    
        private String removeIllegalXmlChars(String s) {
            final Matcher matcher = XML_TAG.matcher(s);
            StringBuffer sb = new StringBuffer();
            while(matcher.find()) {
                String elementName = REMOVE_ILLEGAL_CHARS.matcher(matcher.group("nonXml"))
                        .replaceAll("").trim();
                matcher.appendReplacement(sb, "${first}" + elementName + "${last}");
            }
            matcher.appendTail(sb);
            return sb.toString();
        }
    
        Map convertJson(String json) throws IOException {
            return mapper.readValue(json, new TypeReference>(){});
        }
    
        public String convertJsonToXml(String json) throws IOException {
            return convertToXml(convertJson(json));
        }
    }
    

    Here is a JUnit test for convertJsonToXml:

    @Test
    void convertJsonToXml() throws IOException, ParserConfigurationException, SAXException {
        try(InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("json/customer_sample.json")) {
            String json = new Scanner(in).useDelimiter("\\Z").next();
            String xml = converter.convertJsonToXml(json);
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
            Node first = doc.getFirstChild();
            assertNotNull(first);
            assertTrue(first.getChildNodes().getLength() > 0);
        }
    }
    

提交回复
热议问题