How to convert XML to JSON using only Jackson?

后端 未结 6 1712
无人共我
无人共我 2020-11-30 04:35

I am getting a response from server as XML. But I need to display this in JSON format.

Is there any way to convert it without any third party API? I used Jackson but

6条回答
  •  有刺的猬
    2020-11-30 04:45

    Using jackson

    import com.fasterxml.jackson.dataformat.xml.XmlMapper;
    import java.io.IOException;
    
    public class JsonUtil {
    
        private static XmlMapper XML_MAPPER = new XmlMapper();
        private static ObjectMapper JSON_MAPPER = new ObjectMapper();
    
        public static ObjectMapper getJsonMapper(){
            return JSON_MAPPER;
        }
    
        public static XmlMapper getXmlMapper(){
            return XML_MAPPER;
        }
    
        public static String xmlToJson(String xml){
            try {
                return getJsonMapper().writeValueAsString(getXmlMapper().readTree(xml));
            } catch (IOException e) {
                e.printStackTrace();
                return "";
            }
        }
    }
    

提交回复
热议问题